c++编程:基于#include <iostream> class Complex { public: Complex(double real = 0, double imag = 0) : _real(real), _imag(imag) {} Complex operator+(const Complex& other) const { return Complex(_real + other._real, _imag + other._imag); } Complex operator+(double value) const { return Complex(_real + value, _imag); } friend std::ostream& operator<<(std::ostream& os, const Complex& c) { os << "(" << c._real << ", " << c._imag << "i)"; return os; } private: double _real; double _imag; }; int main() { Complex c1(1, 2); Complex c2(3, 4); double x = 5; std::cout << "c1 = " << c1 << std::endl; std::cout << "c2 = " << c2 << std::endl; std::cout << "x = " << x << std::endl; std::cout << "c1 + c2 = " << c1 + c2 << std::endl; std::cout << "c1 + x = " << c1 + x << std::endl; return 0; }在此基础上修改,实现实现浮点型数据+复数类对象的运算
时间: 2024-02-25 18:57:37 浏览: 66
c++ complex
3星 · 编辑精心推荐
好的,我们可以在Complex类中再重载一个运算符+,使之能够用于浮点型数据与复数类对象之和的运算。具体实现如下:
```c++
#include <iostream>
class Complex {
public:
Complex(double real = 0, double imag = 0) : _real(real), _imag(imag) {}
Complex operator+(const Complex& other) const {
return Complex(_real + other._real, _imag + other._imag);
}
Complex operator+(double value) const {
return Complex(_real + value, _imag);
}
// 重载运算符+,实现浮点型数据+复数类对象的运算
friend Complex operator+(double value, const Complex& c) {
return Complex(c._real + value, c._imag);
}
friend std::ostream& operator<<(std::ostream& os, const Complex& c) {
os << "(" << c._real << ", " << c._imag << "i)";
return os;
}
private:
double _real;
double _imag;
};
int main() {
Complex c1(1, 2);
Complex c2(3, 4);
double x = 5;
std::cout << "c1 = " << c1 << std::endl;
std::cout << "c2 = " << c2 << std::endl;
std::cout << "x = " << x << std::endl;
std::cout << "c1 + c2 = " << c1 + c2 << std::endl;
std::cout << "c1 + x = " << c1 + x << std::endl;
std::cout << "x + c2 = " << x + c2 << std::endl; // 新增加的运算符重载
return 0;
}
```
在上面的代码中,我们在Complex类外部再重载了一个运算符+,使之能够实现浮点型数据+复数类对象的运算。函数签名为:
```c++
friend Complex operator+(double value, const Complex& c);
```
这个函数接受一个浮点数value和一个复数类对象c作为参数,并返回一个新的Complex类对象,表示浮点数与复数对象的和。在函数实现中,我们只需要将浮点数与复数的实部相加即可。
在main函数中,我们新增加了一个测试语句,演示了浮点数与复数对象相加的运算,即x + c2。
希望这个例子对你有所帮助。
阅读全文