c++ complex类的运算符重载如何实现

   2024-09-30 8980
核心提示:在C++中,std::complex是一个模板类,用于表示复数。它已经为你提供了一系列运算符重载,例如+、-、*和/,以及相等和不等运算符

在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成员函数,因为它们不应该修改对象的状态。

 
举报打赏
 
更多>同类物流大全
推荐图文
推荐物流大全
点击排行

网站首页  |  关于我们  |  联系方式 | 网站留言    |  赣ICP备2021007278号