C++类的模板

it2022-05-05  112

#include <iostream> #include <string> #include <stdlib.h> using namespace std; //1、 //类模板的类型指定默认值: //template<typename T=int> 则调用时不用写int: //Father<> f1(12); //如果调用时写了 char : //Father<char> f1(12); //则将默认的 int 覆盖 //2、 //可以有多个: //template<typename T=int, typename Y=char> //调用时: //Father<int, char> f1(12, 'a'); #if 0 //2、 //只有类模板可以指定 模板的参数类型的默认值 template<typename T=int> //err 但是没有报错 void fun(T t) { cout << t << endl; } #endif template<typename T> class Father { public: T a; Father(T t) { a = t; } void show() { cout << a << endl; } void get_a(); }; //类外函数模板 //template<typename T> //void Father<int>::get_a() //{ // cout << a << endl; //} //或者: template<typename T> void Father<T>::get_a() { cout << a << endl; } void main() { //在栈区 Father<int> f1(12); //模板参数列表 //f1.show(); //在堆区 Father<int> *f2 = new Father<int>(124545); f2->get_a(); system("pause"); }

最新回复(0)