声明一个复数类Complex,重载运算符“+”,使之能用于复数的加法运算。参加运算的两个运算量可以都是类对象,也可以其中有一个是整数,顺序任意。运行程序,分别求两个复数之和、整数和复数之和。
时间: 2024-05-14 22:16:30 浏览: 5
以下是实现复数类Complex的代码:
```cpp
#include <iostream>
using namespace std;
class Complex {
private:
double realPart;
double imagPart;
public:
Complex(double real = 0, double imag = 0) {
realPart = real;
imagPart = imag;
}
Complex operator+(const Complex& c) const {
return Complex(realPart + c.realPart, imagPart + c.imagPart);
}
Complex operator+(double d) const {
return Complex(realPart + d, imagPart);
}
friend Complex operator+(double d, const Complex& c) {
return Complex(c.realPart + d, c.imagPart);
}
void display() const {
cout << realPart << " + " << imagPart << "i" << endl;
}
};
int main() {
Complex c1(1, 2);
Complex c2(3, 4);
Complex c3 = c1 + c2;
Complex c4 = c1 + 5;
Complex c5 = 6 + c2;
c3.display();
c4.display();
c5.display();
return 0;
}
```
运行结果:
```
4 + 6i
6 + 2i
9 + 4i
```
可以看到,我们定义了一个复数类Complex,其中包含了实部和虚部两个成员变量,同时重载了“+”运算符,使得它可以用于复数的加法运算。我们还重载了“+”运算符,使得它可以用于复数和整数之间的加法运算,同时保证顺序可以任意。最后,我们在主函数中对复数类进行了测试,分别求了两个复数之和和整数和复数之和。