c++ complex類的運(yùn)算符重載如何實(shí)現(xiàn)

c++
小樊
85
2024-09-10 14:24:00

在C++中,std::complex是一個(gè)模板類,用于表示復(fù)數(shù)。它已經(jīng)為你提供了一系列運(yùn)算符重載,例如+-、*/,以及相等和不等運(yùn)算符。然而,如果你想要自定義一個(gè)復(fù)數(shù)類并實(shí)現(xiàn)這些運(yùn)算符重載,以下是一個(gè)簡(jiǎn)單的示例:

#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;
}

這個(gè)示例中的Complex類實(shí)現(xiàn)了加法、減法、乘法和除法運(yùn)算符重載。同時(shí)還實(shí)現(xiàn)了相等和不等運(yùn)算符重載。注意,這里的運(yùn)算符重載函數(shù)都是const成員函數(shù),因?yàn)樗鼈儾粦?yīng)該修改對(duì)象的狀態(tài)。

0