开发者

I got an error: expected constructor, destructor, or type conversion before '&' token when overloading operator=

I wrote things like that:

template <class T>
MyStack<T>::MyStack()
{
    STACK_SIZE=20;
    STACK_CURRENT=0;
    data=new T[STACK_SIZE];
}

template <class T>
MyStack<T>::MyStack(int thesize)
{
    STACK_SIZE=thesize;
    STACK_CURRENT=0;
    data=new T[STACK_SIZE];
}

template <class T>
MyStack<T>::MyStack(const MyStack& obj)
{
    STACK_SIZE=obj.STACK_SIZE;
    STACK_CURRENT=obj.STACK_CURRENT;
    data=new T[STACK_SIZE];
    for(int i=0; i<STACK_CURRENT; i++)
    {
        data[i]=obj.data[i];
    }
}

template <class T>
MyStack<T>::~MyStack()
{
//do nothing
}
//--------------------Get Error below this line-------------------------
template <class T> MyStack& MyStack<T>::operator=(const MyStack& obj)
//--------------------Get Error in this line---------------------------
{
STACK_SIZE=obj.STA开发者_如何学CCK_SIZE;
STACK_CURRENT=obj.STACK_CURRENT;
data=new T*[STACK_SIZE];
for(int i=0; i<STACK_CURRENT; i++)
{
    data[i]=obj.data[i];
}
return *this;
}

template <class T>bool MyStack<T>::empty()
{
if(STACK_CURRENT==0) return true;
return false;
}

template <class T> T& MyStack<T>::top()
{
return data[STACK_CURRENT-1];
}

template <class T> void MyStack<T>::push(T& obj)
{
if(STACK_CURRENT>=STACK_SIZE-3)
{
    T* tempdata=new T[STACK_SIZE*2];
    for(int i=0; i<STACK_CURRENT; i++)
    {
        tempdata[i]=data[i];
    }
    delete[] data;
    data=new T[STACK_SIZE*2];
    for(int i=0; i<STACK_CURRENT; i++)
    {
        data[i]=tempdata[i];
    }
    STACK_SIZE+=STACK_SIZE;
}
data[STACK_CURRENT]=obj;
STACK_CURRENT++;
}

template <class T> void MyStack<T>::pop()
{
STACK_CURRENT--;
}

template <class T> int MyStack<T>::size()
{
return STACK_CURRENT;
}

My Header has declaration

template<class T> class MyStack
{
public:
MyStack();
MyStack(int);
MyStack(const MyStack&);
~MyStack();
MyStack& operator=(const MyStack&);
bool empty();
T& top();
void push(T&);
void pop();
int size();
private:
int STACK_SIZE;
int STACK_CURRENT;
T* data;
};

But I can't pass compiling, why? Thanks!


Out-class member function definitions should also mention type argument:

template <class T> 
MyStack<T>& MyStack<T>::operator=(const MyStack<T>& obj)
//     ^^^ you forgot this                     ^^^ this too!

Just see these demos:

  • http://www.ideone.com/BEMYn (error)
  • http://www.ideone.com/f6Qzu (fixed)


Templated classes must be fully instantiated at compilation time, not linking time. So,

  • Either you define all functions in the header,
  • Either you use that class only in the compilation unit that defines the functions (so: MyStack.cpp).


Your erroneous line should be

template <class T> MyStack<T>& MyStack<T>::operator=(const MyStack& obj)

instead of

template <class T> MyStack& MyStack<T>::operator=(const MyStack& obj)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜