定义⼀个复数类Complex,重载运算符+、-、*、/,使之能⽤于复数的加减乘除任务⼀:请⽤类的成员函数(或友元函数,选择⼀种)完成运算符的重载
时间: 2023-06-06 09:07:36 浏览: 99
好的,问题已收到。以下是Complex类的重载运算符代码示例:
```c++
class Complex {
private:
double real;
double imag;
public:
Complex(double r = 0, double i = 0) : real(r), imag(i) {}
Complex operator+(const Complex& other) const {
return Complex(real + other.real, imag + other.imag);
}
Complex operator-(const Complex& other) const {
return Complex(real - other.real, imag - other.imag);
}
Complex operator*(const Complex& other) const {
return Complex(real * other.real - imag * other.imag, real * other.imag + imag * other.real);
}
Complex operator/(const Complex& other) const {
double denominator = other.real * other.real + other.imag * other.imag;
return Complex((real * other.real + imag * other.imag) / denominator, (imag * other.real - real * other.imag) / denominator);
}
};
```
其中,`+`、`-`、`*`、`/` 运算符都被重载为成员函数,参数为 `const Complex&`,表示需要另一个 `Complex` 类型的实参。每个运算符都有相应的实现,例如 `+` 运算符的实现是将当前实例的实部和虚部与另一个实例的实部和虚部相加得到一个新的实例。其他运算符的实现可以根据情况类似地进行编写。
阅读全文