定义复数类Complex,包含实部r(double类型)、虚部i(double类型)两个数据成员。 (1)定义含默认参数值的构造函数Complex(double real=0.0, double image=0.0),使用户能够在构造对象的同时为对象赋初值。 (2)以友元函数的方式对复数的加法“+”、减法“-”、乘法“*”三个二元运算符进行重载,以实现复数之间的加、减、乘功能。 (3)以友元函数的方式重载输出运算符“<<”,使得Complex类的对象能够显示其自身信息。
时间: 2023-12-22 19:06:20 浏览: 80
好的,我来帮你解答这个问题。
下面是Complex类的定义及实现:
```cpp
#include <iostream>
using namespace std;
class Complex {
private:
double r; // 实部
double i; // 虚部
public:
// 构造函数
Complex(double real = 0.0, double image = 0.0) : r(real), i(image) {}
// 友元函数:加法运算符重载
friend Complex operator+(const Complex& c1, const Complex& c2) {
return Complex(c1.r + c2.r, c1.i + c2.i);
}
// 友元函数:减法运算符重载
friend Complex operator-(const Complex& c1, const Complex& c2) {
return Complex(c1.r - c2.r, c1.i - c2.i);
}
// 友元函数:乘法运算符重载
friend Complex operator*(const Complex& c1, const Complex& c2) {
double real = c1.r * c2.r - c1.i * c2.i;
double image = c1.r * c2.i + c1.i * c2.r;
return Complex(real, image);
}
// 友元函数:输出运算符重载
friend ostream& operator<<(ostream& os, const Complex& c) {
os << c.r << " + " << c.i << "i";
return os;
}
};
```
使用示例:
```cpp
int main() {
Complex c1(1, 2);
Complex c2(2, 3);
Complex c3 = c1 + c2;
Complex c4 = c1 - c2;
Complex c5 = c1 * c2;
cout << c1 << " + " << c2 << " = " << c3 << endl;
cout << c1 << " - " << c2 << " = " << c4 << endl;
cout << c1 << " * " << c2 << " = " << c5 << endl;
return 0;
}
```
输出结果:
```
1 + 2i + 2 + 3i = 3 + 5i
1 + 2i - 2 - 3i = -1 - 1i
1 + 2i * 2 + 3i = -4 + 7i
```
希望能够帮到你!
阅读全文