Friend Class
- 在一个类中指明其他的类(或者)函数能够直接访问该类中的private和protected成员
注意:friend在类中的声明可以再public、protected和private的如何一个控制域中,而不影响其效果。例如,如果你在protected域中有这样的声明,那么aClass类同样可以访问该类的private成员。
class Node
{
friend class BinaryTree; // class BinaryTree can now access data directly
private:
int data;
int key;
// ...
};
这样BinaryTree就可以直接访问Node中的private的成员了,就像下面这样:
class BinaryTree
{
private:
Node *root;
int find(int key);
};
int BinaryTree::find(int key)
{
// check root for NULL...
if(root->key == key)
{
// no need to go through an accessor function
return root->data;
}
// perform rest of find
}
网友评论