注册 登录
编程论坛 C++教室

C++重载操作符“+”无法进行连续加法,新手求助

江边明月 发布于 2018-12-16 18:52, 1460 次点击
最近在学习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;
}

3 回复
#2
rjsp2018-12-17 09:48
建议你换本教科书

程序代码:
#include <iostream>

class Complex
{
public:
    Complex( int a=0, int b=0 ) : a_(a), b_(b)
    {
    }

private:
    int a_;
    int b_;

    friend Complex operator+( const Complex& lhs, const Complex& rhs );
    friend std::ostream& operator<<( std::ostream& os, const Complex& cpl );
};

Complex operator+( const Complex& lhs, const Complex& rhs )
{
    return Complex( lhs.a_+rhs.a_, lhs.b_+rhs.b_ );
}

std::ostream& operator<<( std::ostream& os, const Complex& cpl )
{
    return os << '(' << cpl.a_ << '+' << cpl.b_ << "i)";
}


using namespace std;

int main(void)
{
    Complex c1(10,20 );
    Complex c2(1, 2);
    cout << c1 << '\n'
         << c2 << '\n';

    Complex c4 = c2 + c1 + c1;
    cout << c4 << endl;
}

#3
江边明月2018-12-18 10:30
回复 2楼 rjsp
谢谢

#4
lyb6612018-12-19 08:59
默认构造函数没有参数,a=0,b=0哪里来的?
设置一个有默认值为0宀构造函数可以的
1