91超碰碰碰碰久久久久久综合_超碰av人澡人澡人澡人澡人掠_国产黄大片在线观看画质优化_txt小说免费全本

溫馨提示×

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
信宜市| 水城县| 商南县| 郑州市| 苍溪县| 灵山县| 林芝县| 郎溪县| 疏附县| 海门市| 罗平县| 泗阳县| 璧山县| 三都| 淳安县| 三亚市| 长顺县| 白沙| 都安| 二连浩特市| 安远县| 新沂市| 独山县| 伊宁市| 敦煌市| 庄浪县| 那坡县| 沾化县| 彰化市| 德阳市| 浦城县| 杭锦后旗| 杂多县| 上思县| 宁波市| 三原县| 莱芜市| 扶风县| 齐河县| 自贡市| 盐源县|