类模板对象的引用?

hailun 2005-10-28 10:41:28
类模板在C++很重要吗?常用吗?

#include<iostream.h>//一处错误
#include<conio.h>
template<class SType>
class stack
{
public:
stack(int size);
~stack()
{
delete []stck;
}
void push(SType i);
SType pop();
private:
int tos,length;
SType *stck;
};
template<class SType>
stack<SType>::stack(int size)
{
stck<SType>::push(SType i)
{cout<<"can not allocate stack memory!"<<endl;
exit(1);
}
length=size;
tos=0;
}
template<class SType>
void stack<SType>::push(SType i)
{if(tos==length)
{cout<<"stack is full.\n";
return;
}
sck[tos]=i;
tos++;
}
template<class SType>
SType stack<SType>::pop()
{if(tos==0)
{cout<<"stack nuderflow.\n";
return 0;
}
tos--;
return stck[tos];
}
template<class SType>
void myfun(stack<SType>&sta)//这个SYype不能换成其它的类型吗?
{cout<<sta.pop()<<endl;
}
void main()
{
stack<int>s(10);
for(int i=14;i<19;i++)
s.push(i);
for(int i=0;i<5;i++)
myfun(s);
cout<<endl;
getch();
}
...全文
86 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
jay0518 2005-10-28
  • 打赏
  • 举报
回复
摸帮很重要
你的程序有不少问题
修改后:
#include<iostream.h>//一处错误
#include<conio.h>
template<class SType>
class stack
{
public:
stack(int size);
~stack()
{
delete []stck;
}
void push(SType i);
SType pop();
private:
int tos,length;
SType *stck;
};
template<class SType>
stack<SType>::stack(int size)
{
stck=new SType[10];
length=size;
tos=0;
}
template<class SType>
void stack<SType>::push(SType i)
{
if(tos==length)
{cout<<"stack is full.\n";
return;
}
stck[tos]=i;
tos++;
}
template<class SType>
SType stack<SType>::pop()
{if(tos==0)
{cout<<"stack nuderflow.\n";
return 0;
}
tos--;
return stck[tos];
}
template<class SType>
void myfun(stack<SType>&sta)//这个SYype不能换成其它的类型吗?
{cout<<sta.pop()<<endl;
}
void main()
{
stack<int>s(10);
for(int i=14;i<19;i++)
s.push(i);
{
for(int i=0;i<5;i++)
myfun(s);
}
cout<<endl;
getch();
}
ifeelhappy 2005-10-28
  • 打赏
  • 举报
回复
哪里是一处错误。。。
hailun 2005-10-28
  • 打赏
  • 举报
回复
谢谢楼上明白了

64,646

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧