c++友元函数如何使用
时间: 2023-12-14 11:02:26 浏览: 34
友元函数是一种特殊的函数,它可以访问类的私有成员和保护成员。在 C++ 中,友元函数需要在类中进行声明,以便可以访问类的私有成员和保护成员。下面是一个简单的示例,演示了如何在 C++ 中使用友元函数:
```c++
#include <iostream>
using namespace std;
class MyClass {
private:
int x;
public:
MyClass() {
x = 0;
}
friend void myFunction(MyClass&);
};
void myFunction(MyClass& c) {
c.x = 10;
cout << "x = " << c.x << endl;
}
int main() {
MyClass obj;
myFunction(obj);
return 0;
}
```
在上面的示例中,`myFunction()` 函数被声明为 `MyClass` 的友元函数。这意味着 `myFunction()` 函数可以访问 `MyClass` 的私有成员 `x`。在 `myFunction()` 函数中,我们将 `x` 设置为 10,并输出其值。
在 `main()` 函数中,我们创建了一个 `MyClass` 的对象 `obj`,并将其传递给 `myFunction()` 函数。在 `myFunction()` 函数中,我们修改了 `obj` 的私有成员 `x` 的值,并输出了其值。
输出结果为:
```
x = 10
```
可以看到,我们成功访问了 `MyClass` 的私有成员 `x`。这就是友元函数在 C++ 中的使用方法。
相关推荐
![](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)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)