template<class T>
class Stack
{
public:
Stack()
{
cout<<"Enter size\n";
cin>>size;
//stackPtr=new int[size];
stackPtr= new T[size];
top =0;
}
~Stack()
{
delete[] stackPtr;
}
void display()
{
cout<<"*****************************\n";
for(int i=0;i<top;i++)
cout<<stackPtr[i]<<endl;
cout<<"*****************************\n";
}
bool Push()
{
int a;
cout<<"Enter element\n";
cin>>a;
if(isFull()==false)
{
stackPtr[top++]=a;
return true;
}
else
return false;
}
bool Pop()
{
if(isEmpty()==false)
{
top--;
return true;
}
else
return false;
}
bool isEmpty()
{
if(top==0)
return true;
else
return false;
}
bool isFull()
{
if(top==size)
return true;
else
return false;
}
private:
//int *stackPtr;
T *stackPtr;
int size;
int top;
//location of the last element added, -1 means empty stack
};
void main()
{
int typeArray;
cout<<"What type of array do you want\n1.Integer\n2.Character\n";
cin>>typeArray;
//If instead of these if statements, i simply
//write Stack<int> Stacks, everything works fine
//So i think theres something wrong with using char or float or ANY other
//datatype?
if(typeArray==1)
Stack <int>Stacks;
else
Stack <float>Stacks;
cout<<"1.PUsh\n2.Pop\n3.Display all\n4.exit\n";
int ch=1;
cin>>ch;
while(ch!=-1)
{
switch(ch)
{
case 1: if(Stacks.Push())
{
cout<<"Stack Full\nPop to enter other values\n";
}
break;
case 2: if(Stacks.Pop()==false)
cout<<"Stack EMpty\n";
break;
case 3: Stacks.display();
break;
case 4: exit(0);
default:cout<<"Reenter you option\n";
break;
}
cout<<"1.PUsh\n2.Pop\n3.Display all\n4.exit\n";
cin>>ch;
}
}
這些是我得到的錯誤。 我使用VS 2010C++ Basic中的類模板
test.cpp(104): error C2065: 'Stacks' : undeclared identifier
test.cpp(104): error C2228: left of '.Push' must have class/struct/union type
is ''unknown-type''
test.cpp(110): error C2065: 'Stacks' : undeclared identifier
test.cpp(110): error C2228: left of '.Pop' must have class/struct/union type
is ''unknown-type''
test.cpp(113): error C2065: 'Stacks' : undeclared identifier
test.cpp(113): error C2228: left of '.display' must have class/struct/union type
is ''unknown-type''
請修復那個可怕的縮進... – Nim
你有沒有想自己修復它?你有沒有在錯誤信息中看到? –