首先,欢迎并感激博友进行知识补充与修正。
#include <iostream>
using namespace std;
class Complex
{
public:
Complex(int a=0, int b=0)
{
this->a = a;
this->b = b;
}
void print()
{
cout << a << "+" << b << "i" << endl;
}
//成员函数实现二元运算符重载
void operator+(Complex &c2)
{
this->a += c2.a;
this->b += c2.b;
}
private:
int a, b;
/*friend Complex operator+(Complex &c1, Complex &c2);*/
};
全局函数实现二元运算符重载,需要声明为友元函数
//Complex operator+(Complex &c1, Complex &c2)
//{
// Complex c;
// c.a = c1.a + c2.a;
// c.b = c1.b + c2.b;
// return c;
//}
int main()
{
/*Complex c1(1, 2), c2(3, 4);
Complex c3 = c1 + c2;
c3.print();*/
Complex c1(1, 2), c2(3, 4);
c1.operator+(c2);
c1.print();
system("pause");
return 0;
}