用运算符重载设计复数类,实现复数的+、-、*、/

#include <iostream>

using namespace std;
class plurality
{
private:
    double a,b;
public:
    plurality(){}
    plurality(double x,double y)
    {
        a=x;
        b=y;
    }
    ~plurality()
    {

    }
    plurality operator+(plurality A)
    {
        return plurality(a+A.a,b+A.b);
    }
    plurality operator-(plurality A)
    {
        return plurality(a-A.a,b-A.b);
    }
    plurality operator*(plurality A)
    {
        return plurality(a*A.a-b*A.b,b*A.a+a*A.b);
    }
    plurality operator/(plurality A)
    {
        return plurality((a*A.a+b*A.b)/(A.a*A.a+A.b*A.b),(b*A.a-a*A.b)/(A.a*A.a+A.b*A.b));
    }
    void show()
    {
        if(b<0)
        {
            cout<<a<<b<<"i"<<endl;
        }
        if(b==0)
        {
            cout<<a<<endl;
        }
        if(b>0)
        {
            cout<<a<<"+"<<b<<"i"<<endl;
        }
    }

};


int main()
{
    plurality A(2,3);
    plurality B(-1,3);
    plurality C;
    C=A+B;
    C.show();
    C=A-B;
    C.show();
    C=A*B;
    C.show();
    C=A+B;
    C.show();

}

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个使用运算符重载设计复数类实现了+、-、*、/运算: ```cpp #include <iostream> using namespace std; class Complex { public: // 构造函数 Complex(double r = 0, double i = 0) : real(r), imag(i) {} // 运算符重载 Complex operator+(const Complex& c2) const { return Complex(real + c2.real, imag + c2.imag); } Complex operator-(const Complex& c2) const { return Complex(real - c2.real, imag - c2.imag); } Complex operator*(const Complex& c2) const { return Complex(real * c2.real - imag * c2.imag, real * c2.imag + imag * c2.real); } Complex operator/(const Complex& c2) const { double denominator = c2.real * c2.real + c2.imag * c2.imag; return Complex((real * c2.real + imag * c2.imag) / denominator, (imag * c2.real - real * c2.imag) / denominator); } // 输出运算符重载 friend ostream& operator<<(ostream& os, const Complex& c) { os << "(" << c.real << ", " << c.imag << "i)"; return os; } private: double real, imag; // 实部和虚部 }; int main() { Complex c1(1, 2), c2(2, 3); cout << "c1 = " << c1 << endl; cout << "c2 = " << c2 << endl; // 法运算 Complex c3 = c1 + c2; cout << "c1 + c2 = " << c3 << endl; // 减法运算 Complex c4 = c1 - c2; cout << "c1 - c2 = " << c4 << endl; // 乘法运算 Complex c5 = c1 * c2; cout << "c1 * c2 = " << c5 << endl; // 除法运算 Complex c6 = c1 / c2; cout << "c1 / c2 = " << c6 << endl; return 0; } ``` 输出结果: ``` c1 = (1, 2i) c2 = (2, 3i) c1 + c2 = (3, 5i) c1 - c2 = (-1, -1i) c1 * c2 = (-4, 7i) c1 / c2 = (0.615385, -0.0769231i) ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值