C++ 复数类 Complex 重载运算符实现与测试

本代码实现了一个名为 Complex 的复数类,并重载了 +, -, *, /, <<, >> 等运算符以实现复数的加减乘除运算以及输入输出操作。

Complex 类结构说明

  • 私有数据成员:

    • 实部 real (double 型)
    • 虚部 imag (double 型)
  • 成员函数:

    • 有参构造函数 Complex(double, double),参数默认值为 0
    • 重载运算符 +:实现两个 Complex 的加法运算
    • 重载运算符 -:实现两个 Complex 的减法运算
    • 重载运算符 *:实现两个 Complex 的乘法运算
    • 重载运算符 /:实现两个 Complex 的除法运算
    • 重载运算符 <<:实现 Complex 对象的格式输出,输出格式为 <实部>+<虚部>i,例如:10.0,10.0+4.7i,10.0-4.7i,-4.7i,0 等
    • 重载运算符 >>:实现 Complex 对象的格式输入,输入格式为 <实部>+<虚部>i,例如:10.0,10.0+4.7i,10.0-4.7i,-4.7i,0 等

代码示例

#include <iostream>
using namespace std;

class Complex {
private:
    double real;
    double imag;
public:
    Complex(double r = 0, double i = 0) : real(r), imag(i) {}

    // 重载运算符 + 
    Complex operator+(const Complex& other) const {
        return Complex(real + other.real, imag + other.imag);
    }

    // 重载运算符 - 
    Complex operator-(const Complex& other) const {
        return Complex(real - other.real, imag - other.imag);
    }

    // 重载运算符 * 
    Complex operator*(const Complex& other) const {
        return Complex(real * other.real - imag * other.imag, real * other.imag + imag * other.real);
    }

    // 重载运算符 / 
    Complex operator/(const Complex& other) const {
        double denominator = other.real * other.real + other.imag * other.imag;
        return Complex((real * other.real + imag * other.imag) / denominator, (imag * other.real - real * other.imag) / denominator);
    }

    // 重载运算符 << 
    friend ostream& operator<<(ostream& out, const Complex& c) {
        out << c.real << (c.imag >= 0 ? '+' : '-') << abs(c.imag) << 'i';
        return out;
    }

    // 重载运算符 >> 
    friend istream& operator>>(istream& in, Complex& c) {
        char sign, i;
        in >> c.real >> sign >> c.imag >> i;
        if (sign != '+' && sign != '-') {
            in.setstate(ios::failbit);
        }
        if (i != 'i') {
            in.setstate(ios::failbit);
        }
        return in;
    }
};

int main() { // 主函数
    Complex c1(1, 1), c2(-1, -1), c3;
    cin >> c1;
    cout << c1 << endl;
    cout << c2 << endl;
    c3 = c1 - c2;
    cout << c3 << endl;
    c3 = c1 + c2;
    cout << c3 << endl;
    c3 = c1 * c2;
    cout << c3 << endl;
    c3 = c1 / c2;
    cout << c3 << endl;
    return 0;
}

输入样例

10.0-4.7i

输出样例

10-4.7i -1-1i 11-3.7i 9-5.7i -14.7-5.3i -2.65+7.35i

算法复杂度

  • 重载运算符:O(1) 时间复杂度
C++ 复数类 Complex 重载运算符实现与测试

原文地址: https://www.cveoy.top/t/topic/oj6Q 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录