读书人

自己定义的类模版 运行时说“=”没有定

发布时间: 2012-03-29 12:53:12 作者: rapoo

自己定义的类模版 运行时说“=”没有定义
本人刚刚接触这个,按照书上写了下面这个程序,是在没有办法让它通过,
希望得到高人指点

我再VC6.0中定义了两个文件
Multiplication Table.cpp和Test.cpp


//Multiplication Table.cpp

#ifndef STACKTP_H_
#define STACKTP_H_

template <class Type>
class Stack
{
private:
enum {MAX = 10};
Type item[MAX];
int top;
public:
Stack();
bool isempty();
bool isfull();
bool push(const Type & item);
bool pop(Type & item);
};

template <class Type>
Stack<Type>::Stack()
{
top=0;
}


template <class Type>
bool Stack<Type>::isempty()
{
return top==0;
}

template <class Type>
bool Stack<Type>::isfull()
{
return top==MAX;
}

template <class Type>
bool Stack<Type>::push(const Type & item)
{
if(top<MAX)
{
item[top++]=item;
return true;
}
else
{
throw("over flow!");
return false;
}
}


template <class Type>
bool Stack<Type>::pop(Type & item)
{
if(top>0)
{
item=item[--top];
return true;
}
else
{
throw("over flow!");
return false;
}
}

#endif


//Test.cpp

#include<iostream>
#include<string>
#include"Multiplication Table.cpp"
using namespace std;



int main(void)
{
Stack<string> st;
string s;
cout<<"Please input a string!\n";
cin>>s;
st.push(s);
if(!st.isempty()) cout<<"push hase successed\n";
st.pop(s);
if(st.isempty()) cout<<"pop hase successed\n";

return 250;
}

错误提示如下

1. error C2679: binary '=' : no operator defined which takes a right-hand operand of type 'const class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >' (o
r there is no acceptable conversion)
2. while compiling class-template member function 'bool __thiscall Stack<class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char>
> >::push(const class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > &)'
执行 cl.exe 时出错.

[解决办法]

C/C++ code
template <class Type>class Stack{private:    enum {MAX = 10};    Type item[MAX];    int top;public:    Stack();    bool isempty();    bool isfull();    bool push(const Type & item);    bool pop(Type & item);};template <class Type>Stack<Type>::Stack(){    top=0;}template <class Type>bool Stack<Type>::isempty(){    return top==0;}template <class Type>bool Stack<Type>::isfull(){    return top==MAX;}template <class Type>bool Stack<Type>::push(const Type & item1){    if(top<MAX)    {        item[top++]=item1;        return true;    }    else      {        throw("over flow!");        return false;    }}template <class Type>bool Stack<Type>::pop(Type & item){    if(top>0)    {        item=item[--top];        return true;    }    else      {        throw("over flow!");        return false;    }}int main(void){    Stack<string> st;    string s;    cout<<"Please input a string!\n";    cin>>s;    st.push(s);    if(!st.isempty()) cout<<"push hase successed\n";    st.pop(s);    if(st.isempty()) cout<<"pop hase successed\n";    return 250;} 

读书人网 >C++

热点推荐