``` // // main.cpp // 類模版與函數模版 // 在類聲明中使用類型參數來聲明通用的類 // Created by mac on 2019/4/6. // Copyright © 2019年 mac. All rights reserved. // 一個類模版中是否支持多種類型的參 ...
//
// main.cpp
// 類模版與函數模版
// 在類聲明中使用類型參數來聲明通用的類
// Created by mac on 2019/4/6.
// Copyright © 2019年 mac. All rights reserved.
// 一個類模版中是否支持多種類型的參數?--可以的
// 在algorithm下已經寫過swap函數了,所以自己再用swap這個名字寫的就通過不了
#include <iostream>
#include <string>
//#include <algorithm>
using namespace std;
template <class genType,int size=50>
class genClass {
public:
genClass(){
cout<<"類模版中執行構造函數"<<endl;
}
~genClass(){
cout<<"類模版中執行析構函數"<<endl;
}
genType storage[size];
};
template <class genType>
void Swap(genType &el1,genType &el2) {
genType tmp=el1;el1=el2;el2=tmp;
}
int main(int argc, const char * argv[]) {
int a=1,b=2;
float c=3.3,d=4.4;
//使用類模版定義對象
genClass<int> intObject1;
genClass<int,100> intObject2;
genClass<float,123> floatObject;
Swap(c,d);
cout<<c<<"\t"<<d<<endl;
return 0;
}