欢迎来到贱贱的博客

扩大
缩小

c++中的友元重载

1 语法

  返回值类型 operator 运算符名称(形参列表)

  {

      重载实体

  }

--------->operator和运算符名称在一起构造成新的函数名

2 案例

 1 #include <iostream>
 2 
 3 using namespace std;
 4 
 5 class Complex
 6 {
 7 public:
 8     
 9     Complex(float x=0,float y=0)
10         :_x(x),_y(y){
11         
12         cout <<"进入构造函数"  << endl;
13         
14     }
15     void dis()
16     {
17         cout << "(" << _x << "," << _y << ")" << endl;
18     }
19     friend const Complex operator+(const Complex &c1, const Complex &c2);
20 private:
21     float _x;
22     float _y;
23 };
24 
25 const Complex operator+(const Complex &c1, const Complex &c2)
26 {
27     return Complex(c1._x + c2._x, c1._y + c2._y);
28 }
29 
30 int main()
31 {
32     Complex c1(2, 3);
33     Complex c2(3, 4);
34     c1.dis();
35     c2.dis();
36 
37     Complex c3 = c1 + c2;//通过在这里打断点你会发现会进入重载函数然后调用构造进行初始化
38     c3.dis();
39     cin.get();
40 }

3 截图

 

posted on 2017-08-06 19:27  L的存在  阅读(254)  评论(0编辑  收藏  举报

导航