首页 > 代码库 > 函数模版和主函数分别在.h .cpp中(要包含.cpp)

函数模版和主函数分别在.h .cpp中(要包含.cpp)

Complex.h


#pragma once
#include<iostream>
using namespace std;//这句还必须加,要不然致错,不懂为啥呢

template <typename T>
class Complex
{
public:
	Complex( T a);
	~Complex();
	Complex operator + (Complex & c1);
public:
	friend ostream & operator  << <T> (ostream &out,  Complex & c2);
private:
	T a;
};

  

Complex.cpp

#include "Complex.h"
template <typename T>
Complex<T>::Complex(T a )
{
	this->a = a;
}

template <typename T>
Complex<T>::~Complex()
{
}

template <typename T>
Complex<T> Complex<T> ::operator + (Complex<T> & c1)
{
	this->a = this->a + c1.a;
	return *this;
}

template <typename T>
ostream & operator << (ostream &out, Complex <T> & c2)
{
	out << c2.a;
	return out;
}

  

test.cpp


#include<iostream>
#include"Complex.cpp"//这里至关重要!!!
using namespace std;

int main()
{
	Complex <int> a(5);

	cout << a;
	system("pause");
	return 0;
}

  要包含.cpp这点异于常类 易错误

函数模版和主函数分别在.h .cpp中(要包含.cpp)