中文字幕av专区_日韩电影在线播放_精品国产精品久久一区免费式_av在线免费观看网站

溫馨提示×

c++ complex類的運算符重載如何實現

c++
小樊
85
2024-09-10 14:24:00
欄目: 編程語言

在C++中,std::complex是一個模板類,用于表示復數。它已經為你提供了一系列運算符重載,例如+-*/,以及相等和不等運算符。然而,如果你想要自定義一個復數類并實現這些運算符重載,以下是一個簡單的示例:

#include<iostream>

class Complex {
public:
    Complex(double real, double imag) : real_(real), imag_(imag) {}

    // Getters
    double real() const { return real_; }
    double imag() const { return imag_; }

    // Operator overloads
    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 {
        double real_part = real_ * other.real_ - imag_ * other.imag_;
        double imag_part = real_ * other.imag_ + imag_ * other.real_;
        return Complex(real_part, imag_part);
    }

    Complex operator/(const Complex& other) const {
        double denominator = other.real_ * other.real_ + other.imag_ * other.imag_;
        double real_part = (real_ * other.real_ + imag_ * other.imag_) / denominator;
        double imag_part = (imag_ * other.real_ - real_ * other.imag_) / denominator;
        return Complex(real_part, imag_part);
    }

    bool operator==(const Complex& other) const {
        return real_ == other.real_ && imag_ == other.imag_;
    }

    bool operator!=(const Complex& other) const {
        return !(*this == other);
    }

private:
    double real_;
    double imag_;
};

int main() {
    Complex a(3, 4);
    Complex b(1, 2);

    Complex c = a + b;
    Complex d = a - b;
    Complex e = a * b;
    Complex f = a / b;

    std::cout << "a + b = (" << c.real() << ", " << c.imag() << ")\n";
    std::cout << "a - b = (" << d.real() << ", " << d.imag() << ")\n";
    std::cout << "a * b = (" << e.real() << ", " << e.imag() << ")\n";
    std::cout << "a / b = (" << f.real() << ", " << f.imag() << ")\n";

    return 0;
}

這個示例中的Complex類實現了加法、減法、乘法和除法運算符重載。同時還實現了相等和不等運算符重載。注意,這里的運算符重載函數都是const成員函數,因為它們不應該修改對象的狀態。

0
汶川县| 通渭县| 偏关县| 临潭县| 兰溪市| 新蔡县| 樟树市| 锦州市| 麦盖提县| 芷江| 揭西县| 武夷山市| 旬阳县| 泰兴市| 阿合奇县| 光山县| 洛川县| 衡山县| 察隅县| 饶阳县| 莒南县| 廉江市| 彰化县| 花莲市| 合阳县| 海淀区| 手机| 凌源市| 梅河口市| 海伦市| 呼伦贝尔市| 定陶县| 巴里| 绍兴市| 高阳县| 二手房| 长顺县| 昌乐县| 贵港市| 达拉特旗| 淳化县|