?? 9_2.cpp
字號(hào):
//9_2.cpp
#include <iostream>
#include <cstdlib>
using namespace std;
struct Student // 結(jié)構(gòu)體Student
{
int id; //學(xué)號(hào)
float gpa; //平均分
};
template <class T> //類(lèi)模板:實(shí)現(xiàn)對(duì)任意類(lèi)型數(shù)據(jù)進(jìn)行存取
class Store
{
private:
T item; // item用于存放任意類(lèi)型的數(shù)據(jù)
int haveValue; // haveValue標(biāo)記item是否已被存入內(nèi)容
public:
Store(void); // 缺省形式(無(wú)形參)的構(gòu)造函數(shù)
T GetElem(void); //提取數(shù)據(jù)函數(shù)
void PutElem(T x); //存入數(shù)據(jù)函數(shù)
};
//以下實(shí)現(xiàn)各成員函數(shù)。
//注意:模板類(lèi)的成員函數(shù),若在類(lèi)外實(shí)現(xiàn),則必須是模板函數(shù)
template <class T> // 缺省形式構(gòu)造函數(shù)的實(shí)現(xiàn)
Store<T>::Store(void): haveValue(0)
{}
template <class T> // 提取數(shù)據(jù)函數(shù)的實(shí)現(xiàn)
T Store<T>::GetElem(void)
{
if (haveValue == 0) // 如果試圖提取未初始化的數(shù)據(jù),則終止程序
{
cout << "No item present!" << endl;
exit(1);
}
return item; // 返回item中存放的數(shù)據(jù)
}
template <class T> // 存入數(shù)據(jù)函數(shù)的實(shí)現(xiàn)
void Store<T>::PutElem(T x)
{
haveValue++; // 將haveValue 置為 TRUE,表示item中已存入數(shù)值
item = x; // 將x值存入item
}
void main(void)
{
Student g= {1000, 23}; //聲明Student類(lèi)型結(jié)構(gòu)體變量的同時(shí)賦以初值
Store<int> S1, S2; //聲明兩個(gè)Store<int>類(lèi)對(duì)象,其中數(shù)據(jù)成員item為int類(lèi)型
Store<Student> S3;//聲明Store<Student>類(lèi)對(duì)象S3,其中數(shù)據(jù)成員item為Student類(lèi)型
Store<double> D; //聲明Store<double>類(lèi)對(duì)象D,其中數(shù)據(jù)成員item為double類(lèi)型
S1.PutElem(3); //向?qū)ο骃1中存入數(shù)據(jù)(初始化對(duì)象S1)
S2.PutElem(-7); //向?qū)ο骃2中存入數(shù)據(jù)(初始化對(duì)象S2)
cout<<S1.GetElem()<<" "<<S2.GetElem()<<endl; //輸出對(duì)象S1和S2的數(shù)據(jù)成員
S3.PutElem(g); //向?qū)ο驞中存入數(shù)據(jù)(初始化對(duì)象D)
cout <<"The student id is "<<S3.GetElem().id << endl; //輸出對(duì)象S3的數(shù)據(jù)成員
cout << "Retrieving object D " ;
cout << D.GetElem() << endl; //輸出對(duì)象D的數(shù)據(jù)成員
// 由于D未經(jīng)初始化,在執(zhí)行函數(shù)D.GetElement()過(guò)程中導(dǎo)致程序終止
}
?? 快捷鍵說(shuō)明
復(fù)制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號(hào)
Ctrl + =
減小字號(hào)
Ctrl + -