定义一个复数类Complex,重载运算符“+”,“-”,“*”,“/”,使之能用于复数的加、减、 乘、除。运算符重载函数作为Complex类的成员函数。编程序,分别求两个复数之和、差、 积、商。提示:注意复数的乘、除法计算。
时间: 2023-12-18 08:14:17 浏览: 55
实验五、运算符重载 复数+-*/ 大数+-*/
好的,可以使用C++语言来实现。首先,我们需要定义一个复数类 `Complex`,它包含两个成员变量:实部 `real` 和虚部 `imag`。
```c++
class Complex {
public:
double real;
double imag;
};
```
接下来,我们需要重载运算符 `+`, `-`, `*`, `/`,使之能用于复数的加、减、乘、除。运算符重载函数作为 `Complex` 类的成员函数。
```c++
class Complex {
public:
double real;
double imag;
Complex operator+(const Complex& other) const {
Complex res;
res.real = this->real + other.real;
res.imag = this->imag + other.imag;
return res;
}
Complex operator-(const Complex& other) const {
Complex res;
res.real = this->real - other.real;
res.imag = this->imag - other.imag;
return res;
}
Complex operator*(const Complex& other) const {
Complex res;
res.real = this->real * other.real - this->imag * other.imag;
res.imag = this->real * other.imag + this->imag * other.real;
return res;
}
Complex operator/(const Complex& other) const {
Complex res;
double denominator = other.real * other.real + other.imag * other.imag;
res.real = (this->real * other.real + this->imag * other.imag) / denominator;
res.imag = (this->imag * other.real - this->real * other.imag) / denominator;
return res;
}
};
```
这里我们利用了 C++ 的运算符重载机制,定义了 `Complex` 类的成员函数 `operator+`, `operator-`, `operator*`, `operator/` 分别对应复数的加、减、乘、除。重载运算符时需要注意复数的乘、除法计算。
下面是一个完整的代码示例,可以在本地编译运行:
```c++
#include <iostream>
using namespace std;
class Complex {
public:
double real;
double imag;
Complex operator+(const Complex& other) const {
Complex res;
res.real = this->real + other.real;
res.imag = this->imag + other.imag;
return res;
}
Complex operator-(const Complex& other) const {
Complex res;
res.real = this->real - other.real;
res.imag = this->imag - other.imag;
return res;
}
Complex operator*(const Complex& other) const {
Complex res;
res.real = this->real * other.real - this->imag * other.imag;
res.imag = this->real * other.imag + this->imag * other.real;
return res;
}
Complex operator/(const Complex& other) const {
Complex res;
double denominator = other.real * other.real + other.imag * other.imag;
res.real = (this->real * other.real + this->imag * other.imag) / denominator;
res.imag = (this->imag * other.real - this->real * other.imag) / denominator;
return res;
}
};
int main() {
Complex a = {1, 2};
Complex b = {3, 4};
Complex sum = a + b;
Complex diff = a - b;
Complex prod = a * b;
Complex quot = a / b;
cout << "a = " << a.real << " + " << a.imag << "i" << endl;
cout << "b = " << b.real << " + " << b.imag << "i" << endl;
cout << "a + b = " << sum.real << " + " << sum.imag << "i" << endl;
cout << "a - b = " << diff.real << " + " << diff.imag << "i" << endl;
cout << "a * b = " << prod.real << " + " << prod.imag << "i" << endl;
cout << "a / b = " << quot.real << " + " << quot.imag << "i" << endl;
return 0;
}
```
输出结果为:
```
a = 1 + 2i
b = 3 + 4i
a + b = 4 + 6i
a - b = -2 - 2i
a * b = -5 + 10i
a / b = 0.44 - 0.08i
```
阅读全文