1 语法

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

  {

      重载实体

  }

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

2 案例

 #include <iostream>

 using namespace std;

 class Complex
{
public: Complex(float x=,float y=)
:_x(x),_y(y){ cout <<"进入构造函数" << endl; }
void dis()
{
cout << "(" << _x << "," << _y << ")" << endl;
}
friend const Complex operator+(const Complex &c1, const Complex &c2);
private:
float _x;
float _y;
}; const Complex operator+(const Complex &c1, const Complex &c2)
{
return Complex(c1._x + c2._x, c1._y + c2._y);
} int main()
{
Complex c1(, );
Complex c2(, );
c1.dis();
c2.dis(); Complex c3 = c1 + c2;//通过在这里打断点你会发现会进入重载函数然后调用构造进行初始化
c3.dis();
cin.get();
}

3 截图

c++中的友元重载-LMLPHP

05-11 22:21