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

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

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

模板类Test

Test.h

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

Test.cpp

#include "Test.h"
using namespace std;
template Test::Test(T a)
{
	this->a = a;
}
template Test::~Test()
{

}
template void Test::printT()
{
	cout << a << endl;
}

主程序

Source.cpp

#include 
#include "Test.h"
#include "Test.cpp"
using namespace std;
int use1(int &c)
{
	c++;
	return c;
}
int use2(int c)
{
	c++;
	return c;
}
template
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(i1, i2) << endl;
	double j1 = 10.253;
	double j2 = 9.635;
	cout << add(j1, j2) << endl;
	cout << "_____________" << endl;
	Test test(12);
	test.printT();
	

	getchar();
}





你可能感兴趣的:(C++)