C++类模板

今天网上找到一个C++类模板的简洁明了的例子:

#include "iostream.h"
#include "stdlib.h"
//结构体
struct Student
{
 int id;
 int age;
};
//类模板
template <class T>
class Store
{
private:
 T item;
 int haveValue;
public:
 Store(void);
    T GetElem(void);
 void PutElem(T x);
};

template <class T>
Store <T>::Store(void):haveValue(0)
{}

template <class T>
T Store <T>::GetElem(void)
{
 //如果试图提取未初始化的程序,则终止程序
 if(haveValue==0)
 {
  cout<<"No item present!"<<endl;
  exit(1);
 }
 return item;
}
//存入数据函数的实现
template <class T>
void Store <T>::PutElem(T x)
{
 haveValue++;
 item = x;
}
void main(void)
{
 Student g={1000,23};
 //声明Student类型结构体变量的同时赋以初值
 Store<int> S1,S2;
 //声明两个Store类对象,其中数据成员item为int类型
 Store<Student> S3;
 //都必须明Store类对象S3,其中数据成员item为Student类型
 Store<double> D;

 S1.PutElem(3);
 S2.PutElem(-7);
 cout<<S1.GetElem()<<" "<<S2.GetElem()<<endl;
 //输出对象S1和S2的数据成员

 S3.PutElem(g);
 cout<<"The Student id is "<<S3.GetElem().id<<endl;
               //输出对象S3的数据成员

 cout<<"Retrieving object D ";
 cout<<D.GetElem()<<endl;
 //由于D未初始化,在执行函数D.GetElement()过程中导致程序终止
}

转载于:https://www.cnblogs.com/limeng/archive/2010/05/13/1734487.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值