C++中friend的使用

2020-06-02  本文已影响0人  Then丶

Friend Class

注意: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

上一篇 下一篇

猜你喜欢

热点阅读