创建复数类complex,其中包含double型数据成员real和imag,分别表示复数的实域和虚域。为complex类重载运算符‘+’和‘-’,用来实现两个复数的加法和减法运算。要求用以下两种方法实现:重载函数为类的友元函数;重载函数为类的友元函数。
时间: 2024-02-20 16:01:13 浏览: 58
下面是使用重载函数为类的成员函数和友元函数实现复数类的代码:
```c++
#include <iostream>
using namespace std;
class complex {
private:
double real; // 实部
double imag; // 虚部
public:
complex(double r = 0, double i = 0) : real(r), imag(i) {}
complex operator+(const complex& c) const; // 重载+运算符为成员函数
friend complex operator-(const complex& c1, const complex& c2); // 重载-运算符为友元函数
void show() const { // 输出复数
cout << "(" << real << "," << imag << ")";
}
};
complex complex::operator+(const complex& c) const {
return complex(real + c.real, imag + c.imag);
}
complex operator-(const complex& c1, const complex& c2) {
return complex(c1.real - c2.real, c1.imag - c2.imag);
}
int main() {
complex c1(1, 2), c2(3, 4), c3;
c3 = c1 + c2;
c3.show(); // 输出(4,6)
c3 = c1 - c2;
c3.show(); // 输出(-2,-2)
return 0;
}
```
在上面的代码中,我们重载了加法运算符`+`为类的成员函数,实现了复数的加法运算。同时,我们重载了减法运算符`-`为友元函数,也实现了复数的减法运算。
需要注意的是,友元函数可以访问类的私有成员,因此我们可以在友元函数中直接访问复数类的实部和虚部。而成员函数则需要使用`this`指针来访问类的私有成员。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)