您的位置:首页 > 编程语言 > C语言/C++

C++中的友元——编程界的老王

2015-08-09 13:13 302 查看
c++中友元类可以访问类的所有域,简直是编程世界的老王。

老王可以得知邻居李的名字,户籍,甚至是 *wife**。

但是老王却不一定知道邻居李的儿子的亲生父亲。

老王的儿子,可以通过老王得知邻居李叔的八卦新闻。

但是老王的儿子和老王一样,并不能知道邻居李叔儿子的亲生父亲。

#include <iostream>
using namespace std;

class Li
{
    friend class LaoWang;
public:
    Li(): name(1), m_home(2), m_wife(3) {}
    ~Li(){ }

public:
    int name;
protected:
    int m_home;
private:
    int m_wife;
};

class LiSon: public Li
{
public:
    LiSon():trueFather(4){}
private:
    int trueFather;
};

class LaoWang
{
public:
    virtual void look(const Li& li) {
        cout << "LaoWang know Li's "
             << endl;
        cout << "name: " << li.name
             << " home: " << li.m_home
             << " wife: " << li.m_wife
             << "." << endl;
    }
};

class LaoWangSon: public LaoWang
{
public:
    void look(const Li& uncleLi) {
        //! cout << "name: " << uncleLi.name << " home: " << uncleLi.m_home << " wife: " << uncleLi.m_wife<< endl;
        cout << "LaoWang's son know" << endl;
        this->LaoWang::look(uncleLi);
    }

};

int main(int, char**)
{
    Li li;
    LaoWang laoWang;

    laoWang.look(li);
    cout << "========" << endl;

    LaoWangSon laoWangSon;
    laoWangSon.look(li);
    cout << "========" << endl;

    cout << "LaoWang only know LiSon's father's ." << endl;
    LiSon liSon;
    laoWang.look(liSon);

    cout << "========"
         << "oh! the firend mean the LaoWang."
         << endl;

    return 0;
}


使用友元类时注意:

* 友元关系不能被继承。

* 友元关系是单向的,不具有交换性。若类B是类A的友元,类A不一定是类B的友元,要看在类中是否有相应的声明。

* 友元关系不具有传递性。若类B是类A的友元,类C是B的友元,类C不一定是类A的友元,同样要看类中是否有相应的申明。

贵圈真乱
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: