http://www.cnblogs.com/zhanggaofeng/p/5661829.html
//類模版與友元函數
#include<iostream>
using namespace std;template<typename T>
class Complex{
public:Complex(T a,T b);void Print() const//const修飾的是this指針{cout << this->Real << ":" <<this->Image<< endl;}/*強調:在類模板里實現友元函數 不可以寫在類的外部,只能在類的內部實現,否則編譯器報錯本質原因是類模板編譯了2次,導致對友元函數也編譯了2次 所以c++編譯器不認可寫在類模板外面的友元函數對于普通類則沒有這個問題*///友元函數friend Complex operator+(Complex &c1, Complex &c2){Complex tempc(c1.Real + c2.Real, c1.Image + c2.Image);return tempc;//匿名對象}//成員函數---成員函數跟友元函數不同,可以在類外面實現Complex operator-(Complex &c2);
private:T Real, Image;
};template<typename T>
Complex<T>::Complex(T a, T b){this->Real = a;this->Image = b;
}template<typename T>
Complex<T> Complex<T>::operator-(Complex<T> &c2){Complex tempc(this->Real - c2.Real, this->Image - c2.Image);return tempc;//匿名對象
}void ProtectA(){Complex<int> c1(3,4);//c1.Print();Complex<int> c2(5, 7);//運算符重載 + 友元函數實現Complex<int> c3 = c1 + c2;c3.Print();/*首先承認運算符重載是一個函數,寫出函數名operator+然后根據操作數,寫出參數列表operator+(Complex<int> &c1,Complex<int> &c2)最后根據接收對象決定返回值,實現函數Complex<int> operator+(Complex<int> &c1,Complex<int> &c2)在類的內部可以省略參數列表,因為類的聲明不分配內存,不需要確定類的大小*/Complex<int> c4 = c2 - c1;/*首先承認運算符重載是一個類內部函數,寫出函數名operator-然后根據操作數,寫出參數列表c1.operator-(Complex<int> &c2);最后根據接收對象決定返回值,實現函數Complex<int> c1.operator-(Complex<int> &c2);在類的內部可以省略參數列表,因為類的聲明不分配內存,不需要確定類的大小 參數列表就是<T>*/c4.Print();}void main(){ProtectA();system("pause");
}