实现复数类

实现复数类

  • 功能实现

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

    #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;
    }
    
已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 1024 设计师:白松林 返回首页