| 网站首页 | 业界新闻 | 小组 | 交易 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
 买学问 - 大牛一对一辅导，有问必答 买学问 - 专业的付费知识问答平台

已结贴   问题点数：20  回复次数：3
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;
}

得分:20

```#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;
}```

得分:0

得分:0

• 4
• 1/1页
• 1