复数的加法运算符重载

Addition operator overloading for complex numbers

本文关键字:运算符 重载      更新时间:2023-10-16

我编写了以下代码来对复数进行基本运算的运算符重载,这里我只放了加法。运行它时,我收到数万亿个错误。我已经看到了其他几篇关于此的帖子,但我刚刚开始学习C++。如果您能大致指出我在运算符重载中犯的错误,我将不胜感激(这与调试无关,但我希望得到一些一般性解释,因为我已经看到了相同运算符重载的示例,但无法理解几个功能,例如使用指针和 const(。提前谢谢。

#include<iostream>
using namespace std;
class Complex 
{
private: 
    double real;
    double imaginary;
public:
    Complex(double r, double i);    
    // addition
    Complex operator+(Complex c1, Complex c2);      
};
Complex::Complex(double r, double i)
{
    real = r;
    imaginary = i;
}
Complex Complex::operator+(Complex c1, Complex c2) 
{
    Complex result;
    result.r = c1.r + c2.r;
    result.i = c1.i + c2.i;
    return result;
}
ostream ostream::operator<<(ostream out, Complex number)
{
    out << number.r << "+" << number.i << endl;
}
int main() {
    Complex y, z;
    Complex sum;
    y = Complex(2, 4);
    z = Complex(3, 0);
    cout << "y is: " << y << endl;
    cout << "z is: " << z << endl;
    sum = y+z;
    cout << "The sum (y+z) is: " << sum << endl;
    return 0;
}

这里有大量的错误,从不正确的重载运算符尝试到使用错误名称的数据成员。 我会逐步完成我所看到的。


将二进制operator+定义为成员函数时,它只需要一个参数,即右侧参数+(左侧隐式*this(。

此外,您的运算符使用不存在的字段 ri - 您可能是指 realimaginary

class Complex
{
    // ...
public:
    // Wrong, will cause compile-time errors:
    // Complex operator+(Complex c1, Complex c2);  
    // Right:
    Complex operator+(Complex c);
};
Complex Complex::operator+(Complex c) 
{
    Complex result;
    result.real = real + c.real;
    result.imaginary = imaginary + c.imaginary;
    return result;
}

或者,您可以将运算符定义为自由函数而不是类的成员,但您必须使其成为类的好友,因为它访问私有成员:

class Complex
{
    // ...
    friend Complex operator+(Complex, Complex);
};
Complex operator+(Complex c1, Complex c2) 
{
    Complex result;
    result.real = c1.real + c2.real;
    result.imaginary = c1.imaginary + c2.imaginary;
    return result;
}

同样,std::ostreamoperator<<重载应该是一个免费函数,需要修复才能使用 realimaginary 。 但是,由于这些成员是Complex私有的,除非您将此运算符设为Complex的朋友,否则这将失败。 由于ostream是抽象类型,不能接受或按值返回实例,因此需要使用引用。 此外,您实际上不会返回任何内容。

class Complex
{
    // ...
    friend ostream & operator<<(ostream &, Complex);
};
ostream & operator<<(ostream & out, Complex number)
{
    out << number.real << "+" << number.imaginary << endl;
    return out;
}

您的 Complex 类缺少默认构造函数,因此您无法像 Complex c; 一样声明变量,因为这需要存在默认构造函数:

class Complex
{
    // ...
public:
    Complex();
};
Complex::Complex() : real(0), imaginary(0) { }