码迷,mamicode.com
首页 > 其他好文 > 详细

类模板的实现与定义相分离

时间:2017-03-19 13:41:29      阅读:191      评论:0      收藏:0      [点我收藏+]

标签:ons   type   模板   需要   turn   out   const   成员   oid   

之前的类模板成员函数都定义在类的内部,但是在实际开发中,往往需要将成员函数的实现放在类的外部,先看一个基础类:

 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 }

这里的学问有很多,友元函数的模板分离有很多要考虑的东西。

类模板的实现与定义相分离

标签:ons   type   模板   需要   turn   out   const   成员   oid   

原文地址:http://www.cnblogs.com/yangguang-it/p/6579640.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!