#include<iostream>
using namespace std;
template<class T>
class Complex{
public:
Complex(T a, T b);
void setComplex(T a,T b);
friend Complex<T> operator+(const Complex<T> &c1, const Complex<T> &c2){
//對于模闆類的友員函數一定要寫在類内!!!不可以再類外實作
T image = c1.image + c2.image;
T real = c1.real + c2.real;
return Complex<T>(real,image);
//這個必須按照這樣寫,不能加個對象!因為類型不确定!
}
friend Complex<T>operator-(const Complex<T> &c1, const Complex<T> &c2){
T image = c1.image - c2.image;
T real = c1.real - c2.real;
friend Complex<T> operator-(const Complex &c1){
return Complex<T> (-c1.real, -c1.image);
void print()const;
private:
T real, image;
};
template <class T>
Complex<T>::Complex(T a, T b){
setComplex(a, b);
void Complex<T>::print()const{
cout << "real=" << real << "image=" << image << endl;
void Complex<T>::setComplex(T a, T b){
real = a;
image = b;
int main(){
Complex<int> a(2, 3);
Complex<int> b(2, 4);
(a + b).print();
(a - b).print();
(-a).print();
system("pause");
return 0;
本文轉自 神迹難覓 51CTO部落格,原文連結:http://blog.51cto.com/ji123/1922587,如需轉載請自行聯系原作者