1、 设计一个复数Complex类,用友元函数重载乘法运算符(*),用成员函数重载除法运算符(/),完成两个复数对象的乘除法。
时间: 2024-02-09 13:12:54 浏览: 23
好的,我来为您设计一个复数Complex类,并重载乘法和除法运算符。
```C++
#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& c) const; //重载乘法运算符
Complex operator/(const Complex& c) const; //重载除法运算符
void display() const { cout << real << " + " << imag << "i" << endl; } //输出函数
};
//重载乘法运算符
Complex Complex::operator*(const Complex& c) const {
double r = real * c.real - imag * c.imag; //计算实部
double i = real * c.imag + imag * c.real; //计算虚部
return Complex(r, i); //返回乘积
}
//重载除法运算符
Complex Complex::operator/(const Complex& c) const {
double denominator = c.real * c.real + c.imag * c.imag; //分母
double r = (real * c.real + imag * c.imag) / denominator; //计算实部
double i = (imag * c.real - real * c.imag) / denominator; //计算虚部
return Complex(r, i); //返回商
}
int main() {
Complex c1(1, 2), c2(3, 4);
Complex c3 = c1 * c2; //计算乘积
Complex c4 = c1 / c2; //计算商
c3.display();
c4.display();
return 0;
}
```
运行结果为:
```
-5 + 10i
0.44 + 0.08i
```
注意在复数除法中,分母不能为0。如果分母为0,程序会崩溃。
阅读全文