请编写函数实现并测试运算符重载的方法。 要求: 1、将运算符重载为成员函数,实现复数加实数、复数减实数的功能; 2、将运算符重载为非成员函数,实现实数加复数、实数减法复数的功能; 3、验证上述函数功能的正确性
时间: 2024-05-01 16:21:50 浏览: 19
以下是实现运算符重载的代码示例:
```c++
#include<iostream>
using namespace std;
class Complex{
public:
Complex(double r = 0, double i = 0):real(r), imag(i){}
Complex operator + (double r){
return Complex(real + r, imag);
}
Complex operator - (double r){
return Complex(real - r, imag);
}
friend Complex operator + (double r, const Complex& c){
return Complex(c.real + r, c.imag);
}
friend Complex operator - (double r, const Complex& c){
return Complex(r - c.real, -c.imag);
}
void print(){
cout<<"("<<real<<","<<imag<<")"<<endl;
}
private:
double real, imag;
};
int main(){
Complex c(1, 2);
Complex res1 = c + 3;
res1.print(); // (4,2)
Complex res2 = c - 1;
res2.print(); // (0,2)
Complex res3 = 2 + c;
res3.print(); // (3,2)
Complex res4 = 5 - c;
res4.print(); // (4,-2)
return 0;
}
```
在上述代码中,我们定义了一个复数类 Complex ,并实现了成员函数运算符重载 + 和 - ,以及非成员函数运算符重载 + 和 - 。其中,成员函数运算符重载的参数是一个实数,用来实现复数加实数、复数减实数的功能;非成员函数运算符重载的参数是一个实数和一个复数对象,用来实现实数加复数、实数减法复数的功能。最后,在 main 函数中测试了这四个运算符重载的功能,输出了运算结果。
运行程序,输出结果为:
```
(4,2)
(0,2)
(3,2)
(4,-2)
```
可以看出,运算符重载的功能实现正确。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)