0

我的代码
错误 C2275: 'T' : 非法使用这种类型作为表达式

我正在尝试定义一个简单的链表并执行一些基本操作,例如交换、分配等。

#ifndef STACK_H
#define STACK_H
#ifndef NODE_H
#define NODE_H

#include<new>
#include<cassert>
#include "string.hpp"

//class INV:TOS->Sn->Sn-1->----------S0->0
//
template <typename T>
class node{
Public:
T data;
node<T>  * next;
// constructors
node(): data(), next(0){};
node (const T& x): data(x), next(0){};  
};

template<typename T>
class stack{
public:
stack();   //default constructor
~stack();           //destructor
stack(const stack<T>&);//copy constructor
void swap(stack<T>&);  //constant time swap
stack<T>& operator = (stack <T>rhs);
bool IsEmpty()const;
bool IsFull()const;
T pop();
void push(const T &);

private:
node<T>  *tos;


};

//Default constructor
template<typename T>
stack< T>::stack(){
tos=0;
}


//Destructor
template<typename T>
stack<typename T>::~stack(){
    while(tos!=0){
        node<T> *temp=tos;
        tos=tos->next;
        delete temp;
    }
}

//swap
template<typename T>
void stack<T>::swap(stack<T>& rhs){
    node<T>*temp=tos;
    tos=rhs.tos;
    rhs.tos=temp;
}

//copy constructor
template<typename T>
stack<T>::stack(const stack<T> &actual)
{
    node<T>*temp = actual.tos;
    *bottom = 0;
    tos=0;
    while(temp!=0)
    {
        if(tos==0)
            {
            tos=new node<T>(temp->data);
            bottom=tos;
            }
        else
        {
            bottom->next=new node<T>(temp->data);
            bottom=bottom->next;
        }
    }
}


//Assignment operator
template<typename T>
stack<T>::stack <T> & operator = (stack <T>rhs){
    swap(rhs);
    return *this;
}


//IsEmpty
 template<typename T>
 bool stack<T>::IsEmpty()const{
  return tos == 0;
 }


 //IsFull
 template <typename T>
 bool stack<T>::IsFull()const{
  node<T>*temp = new(std::noThrow)node<T>();
  if(temp==0)
      return true;
     delete temp;
     return false;
 }

 //pop
 template<typename T>
T stack<T>::pop(){
    assert(!IsEmpty());
    T result = tos->data;
    stack<T>*temp=tos;
    tos = tos->next;
    delete temp;
    return result;
}

//push
template<typename T>
void stack<T>::push(const T& x){
    assert(!IsFull());
    node<T> *temp = new node<T> (x);
    temp->next=tos;
    tos=temp;
}


#endif
#endif

下面是交换构造函数的主要 // 测试 #include "stack.hpp" #include #include #include "string.hpp"

int main(){


stack<int>s1;

s1.push(10);
s1.push(2);
stack<int> s2;

s2.swap(s1);

//assert(s1.IsEmpty());


std::cout<<"Done testing swap."<<std::endl;
system("pause");

return 0;

}
4

1 回答 1

0

至少,您的赋值运算符定义存在问题。定义此运算符的正确方法是:

    //Assignment operator
    template<typename T>
    stack<T>& stack<T>::operator= (stack <T>rhs)
    {
        swap(rhs);
        return *this;
    }
于 2013-11-06T01:24:20.593 回答