首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

初学模板 不知道如何就错了 麻烦大家看看

2012-04-26 
初学模板 不知道怎么就错了 麻烦大家看看[codeC/C++][/code]#includeiostreamusing namespace stdtemp

初学模板 不知道怎么就错了 麻烦大家看看
[code=C/C++][/code]#include<iostream>
using namespace std;

template<class M>
class intStack
{
public:
intStack(int size=10);//构造函数
~intStack();//析构函数
bool Push(int elem);//入栈操作
bool Pop(int &elem); //出栈操作
int Length( ) const; //获取栈中元素的个数
private:
int *data; //指向动态数组的指针
int top; //栈顶指针
int size; //堆栈的容量
};



template<class M>
bool intStack<M>::Push(int elem){
if(top==size)
{data=new M[size];}
top++;
return 1;
}
template<class M>
bool intStack<M>::Pop(){
if(top==0)
{cout<<"栈空"<<endl;return 0;}
top--;
return 0;
}

int main(){
intStack<int>s;
s.intStack();
s.Push(1);
s.Push(2);
s.Push(3);
for(int i=0;i<3;i++)
cout<<"Pop s:"<<s.Pop()<<endl;
return 0;
}


[解决办法]
bool Pop(int &elem); //出栈操作
 =>
bool Pop(); //出栈操作
 
[解决办法]

C/C++ code
template<class M>bool intStack<M>::Pop(int &elem){    if (top == 0)    {        cout << "栈空" << endl;        return false;    }    elem = data[top--];    return true;}
[解决办法]
楼主,你的函数在类里的声明是
bool Pop(int &elem); //出栈操作

但是你的实现部分却是
bool intStack<M>::Pop()

两个参数都不一样,即使不用模板,也会出错。
[解决办法]
C/C++ code
template<class M>class intStack{public:intStack(int size=10);//构造函数~intStack();//析构函数bool Push(int elem);//入栈操作bool Pop(); //出栈操作int Length( ) const; //获取栈中元素的个数private:int *data; //指向动态数组的指针int top; //栈顶指针int size; //堆栈的容量};template<class M>bool intStack<M>::Push(int elem){if(top==size){data=new M[size];}top++;return 1;}template<class M>bool intStack<M>::Pop(){//声明和定义不一致。if(top==0){cout<<"栈空"<<endl;return 0;}top--;return 0;}int main(){intStack<int>s;//s.intStack();//构造函数式不能显示调用的。s.Push(1);s.Push(2);s.Push(3);for(int i=0;i<3;i++)cout<<"Pop s:"<<s.Pop()<<endl;system("pause");return 0;}
[解决办法]
构造函数不能显式调用的,像4楼说的,注释掉。
[解决办法]
看4楼,类对象声明时编译器会生成构造函数的代码,不用手动调用
探讨

bool Pop(int &amp;elem); //出栈操作
=>
bool Pop(); //出栈操作
改了之后还是有错误

error C2039: 'intStack' : is not a member of 'intStack<int>'

[解决办法]
你没有编写构造函数和析构函数的代码


探讨

注释掉了
可是链接的时候不能通过
error LNK2001: unresolved external symbol "public: __thiscall intStack<int>::~intStack<int>(void)" (??1?$intStack@H@@QAE@XZ)
error LNK2001: unresolved external s……

热点排行