之前的类模板成员函数都定义在类的内部,但是在实际开发中,往往需要将成员函数的实现放在类的外部,先看一个基础类:
1 #include<iostream> 2 using namespace std; 3 4 class Complex { 5 friend Complex operator + (Complex &c1, Complex &c2); 6 friend ostream& operator<<(ostream &out, const Complex& c); 7 public: 8 Complex(int a = 0, int b = 0) 9 { 10 this->a = a; 11 this->b = b; 12 } 13 void printfCom() 14 { 15 cout << "a: " << a << " b: " << b << endl; 16 } 17 private: 18 int a; 19 int b; 20 }; 21 Complex operator + (Complex &c1, Complex &c2) 22 { 23 Complex sum; 24 sum.a = c1.a + c2.a; 25 sum.b = c1.b + c2.b; 26 return sum; 27 } 28 ostream& operator<<(ostream &out, const Complex& c) 29 { 30 out << "a: " << c.a << " b: " << c.b << endl; 31 return out; 32 } 33 int main() 34 { 35 Complex c1(10,20); 36 Complex c2(20, 30); 37 Complex c3 = c1 + c2; 38 cout << c3 << endl; 39 40 cout << "hello...\n"; 41 return 0; 42 }
然后把上面的代码改成类模板:
1 #include<iostream> 2 using namespace std; 3 4 template<typename T> 5 class Complex { 6 template<typename T> 7 friend Complex<T> operator + (Complex<T> &c1, Complex<T> &c2); 8 template<typename T> 9 friend ostream& operator << (ostream &out, const Complex<T>& c); 10 public: 11 Complex(T a , T b ) 12 { 13 this->a = a; 14 this->b = b; 15 } 16 Complex() 17 { 18 this->a = 0; 19 this->b = 0; 20 } 21 void printfCom() 22 { 23 cout << "a: " << a << " b: " << b << endl; 24 } 25 private: 26 T a; 27 T b; 28 }; 29 template<typename T> 30 Complex<T> operator + (Complex<T> &c1, Complex<T> &c2) 31 { 32 Complex<T> sum; 33 sum.a = c1.a + c2.a; 34 sum.b = c1.b + c2.b; 35 return sum; 36 } 37 template<typename T> 38 ostream& operator<< (ostream &out, const Complex<T>& c) 39 { 40 out << "a: " << c.a << " b: " << c.b << endl; 41 return out; 42 } 43 int main() 44 { 45 Complex<int> c1(10,20); 46 Complex<int> c2(20, 30); 47 Complex<int> c3 = c1 + c2; 48 cout << c3 << endl; 49 50 cout << "hello...\n"; 51 return 0; 52 }
这里的学问有很多,友元函数的模板分离有很多要考虑的东西。
时间: 2024-11-01 13:47:29