定义复数类,重载复数的乘法“*” 运算符,完成两个复数的乘法运算。(使用c++,采用友元函数)
时间: 2024-02-23 08:01:47 浏览: 85
好的,以下是一个简单的复数类定义和乘法运算符重载的示例代码:
```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;
}
friend Complex operator* (const Complex& c1, const Complex& c2); // 友元函数声明
void display() { // 显示复数
cout << real << " + " << imag << "i" << endl;
}
};
Complex operator* (const Complex& c1, const Complex& c2) { // 乘法运算符重载
double r = c1.real * c2.real - c1.imag * c2.imag;
double i = c1.real * c2.imag + c1.imag * c2.real;
return Complex(r, i);
}
int main() {
Complex c1(1, 2);
Complex c2(3, 4);
Complex c3 = c1 * c2; // 复数乘法
c3.display();
return 0;
}
```
在上面的示例代码中,我们定义了一个复数类`Complex`,其中包含实部和虚部两个成员变量,以及构造函数和显示函数。然后我们使用友元函数重载了乘法运算符“*”,实现了两个复数的乘法运算。最后在主函数中,我们定义两个复数对象`c1`和`c2`,并将它们相乘得到结果`c3`,最后显示出来。
阅读全文
相关推荐








