请编写函数实现并测试运算符重载的方法。 要求: 1、将运算符重载为成员函数,实现复数加实数、复数减实数的功能; 2、将运算符重载为非成员函数,实现实数加复数、实数减法复数的功能; 3、验证上述函数功能的正确性。
时间: 2024-05-07 15:18:00 浏览: 25
运算符重载实例.
好的,我来编写实现代码。首先需要定义一个复数类:
```cpp
class Complex {
public:
Complex(double r = 0, double i = 0) : real(r), imag(i) {}
Complex(const Complex& c) : real(c.real), imag(c.imag) {}
Complex& operator=(const Complex& c) {
real = c.real;
imag = c.imag;
return *this;
}
Complex operator+(const double& d) const {
return Complex(real + d, imag);
}
Complex operator-(const double& d) const {
return Complex(real - d, imag);
}
friend Complex operator+(const double& d, const Complex& c) {
return Complex(d + c.real, c.imag);
}
friend Complex operator-(const double& d, const Complex& c) {
return Complex(d - c.real, -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;
};
```
这里实现了复数加实数、复数减实数的成员函数重载,以及实数加复数、实数减法复数的非成员函数重载。最后重载了 `<<` 运算符,用于输出。
接下来我们来测试一下:
```cpp
int main() {
Complex c1(1, 2);
Complex c2 = c1 + 3;
Complex c3 = c1 - 3;
Complex c4 = 4 + c1;
Complex c5 = 4 - c1;
std::cout << "c1 = " << c1 << std::endl;
std::cout << "c2 = " << c2 << std::endl;
std::cout << "c3 = " << c3 << std::endl;
std::cout << "c4 = " << c4 << std::endl;
std::cout << "c5 = " << c5 << std::endl;
return 0;
}
```
输出结果如下:
```
c1 = 1+2i
c2 = 4+2i
c3 = -2+2i
c4 = 5+2i
c5 = 3-2i
```
可以看到,运算符重载的功能实现正确。
阅读全文