温馨提示×

c++重载运算符怎么实现复数加减

c++
小亿
86
2024-03-15 17:14:56
栏目: 编程语言

要实现复数的加减操作符重载,可以重载加法运算符"+“和减法运算符”-"。以下是一个示例代码:

#include <iostream>

class Complex {
public:
    double real;
    double imag;

    Complex(double r, double i) : real(r), imag(i) {}

    Complex operator+(const Complex& other) {
        return Complex(real + other.real, imag + other.imag);
    }

    Complex operator-(const Complex& other) {
        return Complex(real - other.real, imag - other.imag);
    }
};

int main() {
    Complex a(1.0, 2.0);
    Complex b(3.0, 4.0);

    Complex c = a + b;
    Complex d = a - b;

    std::cout << "a + b = " << c.real << " + " << c.imag << "i" << std::endl;
    std::cout << "a - b = " << d.real << " + " << d.imag << "i" << std::endl;

    return 0;
}

在上面的示例中,我们定义了一个名为Complex的类来表示复数,重载了加法运算符和减法运算符。在main函数中,我们创建了两个复数a和b,并使用重载的加法和减法运算符来计算它们的和与差。最后输出结果。

通过重载运算符,我们可以像内置类型一样对自定义类对象进行加减操作,使得代码更加直观和易读。

0