1、 设计一个复数Complex类,用友元函数重载乘法运算符(*),用成员函数重载除法运算符(/),完成两个复数对象的乘除法。
时间: 2024-02-22 14:56:00 浏览: 19
好的,我会根据您的要求来设计复数Complex类,并重载乘法运算符和除法运算符。以下是代码实现:
```C++
#include <iostream>
using namespace std;
class Complex {
private:
double real, imag; // 实部和虚部
public:
// 构造函数
Complex(double r = 0, double i = 0) : real(r), imag(i) {}
// 友元函数重载乘法运算符
friend Complex operator*(const Complex& c1, const Complex& c2) {
return Complex(c1.real * c2.real - c1.imag * c2.imag, c1.real * c2.imag + c1.imag * c2.real);
}
// 成员函数重载除法运算符
Complex operator/(const Complex& c) {
double denominator = c.real * c.real + c.imag * c.imag;
return Complex((real * c.real + imag * c.imag) / denominator, (imag * c.real - real * c.imag) / denominator);
}
// 输出复数
void print() {
cout << real << " + " << imag << "i" << endl;
}
};
int main() {
Complex c1(1, 2);
Complex c2(3, 4);
Complex c3 = c1 * c2;
cout << "c1 * c2 = ";
c3.print();
Complex c4 = c1 / c2;
cout << "c1 / c2 = ";
c4.print();
return 0;
}
```
在上面的代码中,我们定义了一个Complex类,用于表示复数。其中,类的私有成员包括实部和虚部,我们用构造函数来初始化这两个成员变量。接着,我们重载了乘法运算符和除法运算符,分别用友元函数和成员函数来实现。最后,我们编写了一个print函数,用于输出复数。
在main函数中,我们创建了两个复数对象c1和c2,并分别进行乘法和除法运算,并输出结果。
希望这段代码能够帮助到您!