定义一个复数类complex,重载运算符“+”"-""×""÷",使之能用于复数的加法运算
时间: 2024-06-04 11:03:56 浏览: 144
定义复数类Complex,进行运算符重载
5星 · 资源好评率100%
好的,定义一个复数类complex,可以包含两个成员变量:实部real和虚部imaginary。同时,可以定义构造函数、析构函数以及重载运算符“+”、“-”、“*”和“/”来实现复数的加减乘除运算。具体实现如下:
```
class complex {
public:
complex(double r = 0, double i = 0): real(r), imaginary(i) {} // 构造函数
~complex() {} // 析构函数
// 重载运算符
complex operator+(const complex& c) const {
return complex(real + c.real, imaginary + c.imaginary);
}
complex operator-(const complex& c) const {
return complex(real - c.real, imaginary - c.imaginary);
}
complex operator*(const complex& c) const {
double r = real * c.real - imaginary * c.imaginary;
double i = real * c.imaginary + imaginary * c.real;
return complex(r, i);
}
complex operator/(const complex& c) const {
double denominator = c.real * c.real + c.imaginary * c.imaginary;
double r = (real * c.real + imaginary * c.imaginary) / denominator;
double i = (imaginary * c.real - real * c.imaginary) / denominator;
return complex(r, i);
}
private:
double real; // 实部
double imaginary; // 虚部
};
```
当我们定义了这个类之后,就可以直接使用“+”、“-”、“*”和“/”运算符进行复数的加减乘除运算了。例如:
```
complex a(1, 2);
complex b(3, 4);
complex c = a + b; // 复数相加
complex d = a - b; // 复数相减
complex e = a * b; // 复数相乘
complex f = a / b; // 复数相除
```
阅读全文