# 实现复数类

## 实现复数类

• 功能实现

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

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


06-12

06-27
03-03 204
09-23 1349
02-16 1万+
08-04 7734
02-28 275
07-31 731
02-18 330
03-12 5338
03-25 306
01-15 1458
10-27 299
08-22 6452
07-10 528
©️2020 CSDN 皮肤主题: 1024 设计师:白松林