实现复数类

实现复数类

  • 功能实现

    • 封装数据,包括实部和虚部
    • 重载加减乘除
    • 重载流输入输出
  • 代码

    #include <iostream>
    #include <algorithm>
    #include <vector>
    #include <queue>
    #include <cstring>
    using namespace std;
    
    class Complex
    {
    public:
      	Complex(double Real=0, double Image=0) : real{ Real }, image{ Image } {}
      	Complex(const Complex& a) : Complex(a.real, a.image) {}
    private:
      	double real;
      	double image;
        friend ostream& operator<<(ostream &o, Complex &c); 
        friend ostream& operator<<(ostream &o, Complex &&c); 
        friend istream& operator>>(istream& i, Complex& c); 
        friend Complex operator+(const Complex &a, const Complex &b);
        friend Complex operator-(const Complex &a, const Complex &b);
        friend Complex operator*(const Complex &a, const Complex &b);
        friend Complex operator/(const Complex &a, const Complex &b);
    };
    
    ostream& operator<<(ostream &o, Complex &c) {
        return o << "(" << c.real << (c.image < 0 ? "" : "+") << c.image << "i)";
    }
    
    ostream& operator<<(ostream &o, Complex &&c) {
        return o << "(" << c.real << (c.image < 0 ? "" : "+") << c.image << "i)";
    }
    
    istream& operator>>(istream& i, Complex& c) {
        return i >> c.real >> c.image;
    }
    
    Complex operator+(const Complex &a, const Complex &b) {
        return Complex{a.real + b.real, a.image + b.image};
    }
    
    Complex operator-(const Complex &a, const Complex &b) {
        return Complex{a.real - b.real, a.image - b.image};
    }
    
    Complex operator*(const Complex &a, const Complex &b) {
        return Complex{a.real * b.real - a.image * b.image,
                       a.real * b.image + a.image * b.real
                };
    }
    
    Complex operator/(const Complex &a, const Complex &b) {
        Complex temp(b.real, -b.image);
        Complex num = a * b;
        double den = b.real * b.real + b.image * b.image;
        Complex c(num.real / den, num.image / den);
        return c;
    }
    
    int main() {
      	Complex z1, z2;
      	cin >> z1;
      	cin >> z2;
      	cout << z1 << " " << z2 << endl;
      	cout << z1 + z2 << endl;
      	cout << z1 - z2 << endl;
      	cout << z1*z2 << endl;
      	cout << z1 / z2 << endl;
    
      	return 0;
    }
    
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值