初学模板 不知道怎么就错了 麻烦大家看看
[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(); //出栈操作
[解决办法]
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()
两个参数都不一样,即使不用模板,也会出错。
[解决办法]
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楼,类对象声明时编译器会生成构造函数的代码,不用手动调用