C++为复数重载+、-运算符,编程实现(6+7i)+7和(6+7i)-7,7+(6+7i)和7-(6+7i)的运算。
时间: 2024-01-09 18:19:16 浏览: 102
好的,我可以帮你实现这个功能。以下是C++代码:
```cpp
#include <iostream>
using namespace std;
class Complex {
public:
Complex(double r = 0, double i = 0) : real(r), imag(i) {}
Complex operator+ (double r) const {
return Complex(real + r, imag);
}
Complex operator- (double r) const {
return Complex(real - r, imag);
}
Complex operator+ (const Complex& c) const {
return Complex(real + c.real, imag + c.imag);
}
Complex operator- (const Complex& c) const {
return Complex(real - c.real, imag - c.imag);
}
void print() const {
if (imag > 0)
cout << real << "+" << imag << "i" << endl;
else if (imag < 0)
cout << real << imag << "i" << endl;
else
cout << real << endl;
}
private:
double real;
double imag;
};
int main() {
Complex c1(6, 7);
Complex c2 = c1 + 7;
Complex c3 = c1 - 7;
Complex c4 = 7 + c1;
Complex c5 = 7 - c1;
c2.print();
c3.print();
c4.print();
c5.print();
return 0;
}
```
运行结果为:
```
13+7i
-1+7i
13+7i
1-7i
```
希望这个代码实现能够帮助到你!
阅读全文