理解友元和成员函数两种实现复数加法的方式
#include<iostream>
using namespace std;
class Complex
{
public:
Complex(float x = 0, float y = 0)
:_x(x), _y(y) {}
//friend Complex operator + (Complex & a, Complex &b);
const Complex operator+(Complex & another);
void dis()
{
cout << "(" << _x << "," << _y << ")" << endl;
}
Complex & operator+=(const Complex &another);
private:
float _x;
float _y;
};
/*
Complex operator+(Complex &a, Complex &b)
{
Complex t;
t._x = a._x + b._x;
t._y = a._y + b._y;
return t;
}*/
const Complex Complex::operator+(Complex & another)
{
Complex t;
t._x = _x + another._x;
t._y = _y + another._y;
return t;
}
Complex & Complex::operator+=(const Complex &another)
{
_x += another._x;
_y += another._y;
return *this;
}
int main()
{
Complex c1(1, 2), c2(2, 3);
Complex c = c1 + c2; // operator+(c1,c2), c1.operator+(c2)
c1.dis();
c2.dis();
c.dis();
c1 += c2;
c1.dis();
system("pause");
return 0;
}