c++ 友元机制
友元(friend)机制允许一个类将对其非私有成员的访问权授予给指定的函数或类。
友元以关键字friend(在类定义的内部)声明。通常将友元声明成组的放在类定义的开始或结尾。
class Screen { // Window_Mgr members can access private parts of class Screen friend class Window_Mgr; … } Window_Mgr& Window_Mgr::relocate(Screen::index r, Screen::index c, Screen& s) { s.height += r; s.width += c; return *this; }
因为Window_Mgr是Screen的友元,所以Window_Mgr的成员函数中能够访问Screen的私有成员。
友元也可以是其他类的成员函数,或者是普通的非成员函数。
class Screen { // Window_Mgr must be defined before class Screen friend Window_Mgr& Window_Mgr::relocate(Window_Mgr::index, Window_Mgr::index, Screen&); … }
友元声明将已命名的类或非成员函数引入到外围作用域中。友元函数可以在类的内部定义,该函数的作用域扩展到包围该类定义的作用域。
用友元引入的类名和函数(定义或声明),可以像预先(前向)声明一样使用:
class X { friend class Y; friend void f() { /* ok to define friend function in the class body */ } }; class Z { Y * y; // ok: declaration for class Y introduced by friend in X void g() { return ::f(); } // ok: declaration of f introduced by X; };
对于重载函数,类必须将重载函数集中的每一个希望设为友元的函数都分别声明为友元。
【学习资料】 《c++ primer》