亚洲激情专区-91九色丨porny丨老师-久久久久久久女国产乱让韩-国产精品午夜小视频观看

溫馨提示×

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
郴州市| 彰化县| 普宁市| 铜梁县| 鸡西市| 湘潭市| 澄江县| 工布江达县| 哈巴河县| 通州区| 英超| 永德县| 苍梧县| 南溪县| 彩票| 衡南县| 米泉市| 孟津县| 台南县| 东阿县| 玛曲县| 灵石县| 庆云县| 保康县| 西吉县| 隆尧县| 德惠市| 清水河县| 河南省| 威海市| 南岸区| 永德县| 筠连县| 措美县| 石棉县| 盐津县| 乳山市| 兴化市| 三都| 内黄县| 佛教|