标签:
1 #include <iostream> 2 using namespace std; 3 4 template <typename T1, typename T2> 5 class complex 6 { 7 public: 8 T1 real; 9 T2 imag; 10 complex(); 11 complex(T1 r, T2 i); 12 complex(const complex<T1, T2> &R); 13 complex &operator=(const complex<T1, T2> &R); 14 }; 15 16 template <typename T1, typename T2> complex<T1, T2>::complex():real(0),imag(0) 17 { 18 } 19 20 template <typename T1, typename T2> complex<T1, T2>::complex(T1 r, T2 i) 21 { 22 real = r; 23 imag = i; 24 } 25 26 template <typename T1, typename T2> complex<T1, T2>::complex(const complex<T1, T2> &R) 27 { 28 real = R.real; 29 imag = R.imag; 30 } 31 32 template <typename T1, typename T2> complex<T1, T2> &complex<T1, T2>::operator=(const complex<T1, T2> &R) 33 { 34 real = R.real; 35 imag = R.imag; 36 return *this; 37 } 38 39 template <typename T1, typename T2> ostream &operator<<(ostream &out, const complex<T1, T2> &R) 40 { 41 out<<"real:"<<R.real<<" imag:"<<R.imag; 42 return out; 43 } 44 45 template <typename T1, typename T2> complex<T1, T2> operator+(const complex<T1, T2> &L, const complex<T1, T2> &R) 46 { 47 complex<T1, T2> sum; 48 sum.real = L.real + R.real; 49 sum.imag = L.imag + R.imag; 50 return sum; 51 } 52 53 int main() 54 { 55 complex<int, int> a(2,3), b(3, 2); 56 complex<int, int> c = a + b; 57 cout<<c<<endl; 58 }
标签:
原文地址:http://www.cnblogs.com/yangzhouyyz/p/5059898.html