美文网首页
C++中friend的使用

C++中friend的使用

作者: Then丶 | 来源:发表于2020-06-02 16:11 被阅读0次

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
}

原文: https://blog.csdn.net/Andy_YF/article/details/7062347

相关文章

网友评论

      本文标题:C++中friend的使用

      本文链接:https://www.haomeiwen.com/subject/rdnuzhtx.html