标签:初始化 get src 构造函数 std str end cout include
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 截图
标签:初始化 get src 构造函数 std str end cout include
原文地址:http://www.cnblogs.com/lanjianhappy/p/7295703.html