友元(friend)

定义

A friend of a class is a function or class that is given permission to use the private and protected member
names from the class. A class specifies its friends, if any, by way of friend declarations. Such declarations give
special access rights to the friends, but they do not make the nominated friends members of the befriending
class.

简单理解

友元可以分为友元函数和友元类。添加了friend关键字的它类或者函数拥有本类的所有访问权限。

举例

// 友元函数
class X {
int a;
friend void friend_set(X*, int);
public:
void member_set(int);
};
void friend_set(X* p, int i) { p->a = i; }
void X::member_set(int i) { a = i; }
void f() {
X obj;
friend_set(&obj,10);
obj.member_set(10);
}

// 友元类
class A {
class B { };
friend class X;
};
struct X : A::B { // OK: A::B accessible to friend
A::B mx; // OK: A::B accessible to member of friend
class Y {
A::B my; // OK: A::B accessible to nested member of friend
};
};
posted @ 2017-03-28 16:16  zyh_think  阅读(183)  评论(0编辑  收藏  举报