1. 程式人生 > >函數模版和主函數分別在.h .cpp中(要包含.cpp)

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

spa end pragma test ios his 函數 private ()

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)