定义一个复数类,使之能用于复数的加减乘除,运算符重载函数作为成员函数,编写程序,分别求两个复数之和差商积
时间: 2023-06-01 07:08:02 浏览: 83
以下是示例代码:
```
#include <iostream>
using namespace std;
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);
}
// 打印复数
void print() const {
cout << real << "+" << imag << "i" << endl;
}
};
int main() {
Complex a(2, 3), b(4, 5);
Complex c = a + b; // 求和
c.print();
Complex d = a - b; // 求差
d.print();
Complex e = a * b; // 求积
e.print();
Complex f = a / b; // 求商
f.print();
return 0;
}
```
运行程序后,会输出以下结果:
```
6+8i
-2-2i
-7+22i
0.560976+-0.0487805i
```
其中,第一行表示两个复数的和,第二行表示两个复数的差,第三行表示两个复数的积,第四行表示两个复数的商。