C++类模板 .h和.cpp文件要写在一起||要在主函数main中用#include "Test.h" Test是模板类名

来源:互联网 发布:网络管理软件排行榜 编辑:程序博客网 时间:2024/05/21 19:48

最好要将C++类模板的.h和.cpp文件的内容一起写在.h文件中,不要分开

C++模板类和模板函数示例:

模板类Test

Test.h

#pragma once#include <iostream>using namespace std;template<class T>class Test{public:T a;public:Test(T a);~Test();void printT();};
Test.cpp

#include "Test.h"using namespace std;template<class T> Test<T>::Test(T a){this->a = a;}template<class T> Test<T>::~Test(){}template<class T> void Test<T>::printT(){cout << a << endl;}

主程序

Source.cpp

#include <iostream>#include "Test.h"#include "Test.cpp"using namespace std;int use1(int &c){c++;return c;}int use2(int c){c++;return c;}template<typename T>T add(T a, T b){return a + b;}int main(){int a;a = 39;cout << a << endl;cout << use1(a) << endl;cout << a << endl;int b;b = 39;cout << b << endl;cout << use2(b) << endl;cout << b << endl;cout << "_____________" << endl;int i1=10, i2=20;cout << add<int>(i1, i2) << endl;double j1 = 10.253;double j2 = 9.635;cout << add<double>(j1, j2) << endl;cout << "_____________" << endl;Test<int> test(12);test.printT();getchar();}





0 0