C++重载操作符“+”无法进行连续加法,新手求助
最近在学习C++,在重载操作符遇到困难,重载“+”操作符后,只能进行a+b, 无法进行a+b+c这样的操作,这是什么原因?
求各位大神,告诉小弟如何解决。
以下是代码:
#include <iostream>
using namespace std;
class Complex
{
public:
Complex()
{
this->a = 0;
this->b = 0;
}
Complex(int a, int b)
{
this->a = a;
this->b = b;
}
//提供一个打印虚数的方法
void print()
{
cout << "(" << a << "+ " << b << " i )" << endl;
}
friend Complex operator+(Complex &c1, Complex &c2);
private:
int a;
int b;
};
Complex operator+(Complex &c1, Complex &c2)
{
Complex temp(c1.a + c2.a, c1.b + c2.b);
return temp;
}
int main(void)
{
Complex c1(10, 20);
Complex c2(1, 2);
c1.print();
c2.print();
// Complex c4 = c1 + c2 ; //可以运行
// c4.print();
Complex c4 = c2 + c1 + c1; //错误,为什么?
c4.print();
return 0;
}