友元机制允许一个类讲对其非公有成员的访问权授予指定的函数或类。友元的声明以关键字friend开始。它只能出现在类定义的内部。友元声明可以出现在类中的任何地方:友元不是授予友元关系的那个类的成员,所以他们不受其声明出现部分的访问控制影响。通常,将友元声明成组地放在类定义的开始或结尾是个好注意。
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class boy{
public:
touch(string str);
not_only_touch(string str);
};
class girl{
public:
friend boy::touch(string str);
private:
string mimi;
string sthElse;
};
int main(void)
{
return 0;
}friend声明对象可以是类或函数。
friend boy; or friend boy::touch(string str);对与重载函数,需要对每个希望设为友元的函数都声明为函数。
本文介绍了C++中的友元机制,解释了如何通过友元声明使一个类能够访问另一个类的非公有成员。友元可以是函数或类,并且可以在类定义的任意位置声明。
2323

被折叠的 条评论
为什么被折叠?



