友元

作者: 温柔倾怀 | 来源:发表于2020-04-29 15:00 被阅读0次

    友元的目的:让一个函数或者类访问一个类中的私有成员

    关键字: friend

    1. 全局函数做友元

    class Building
    {
        //goodFriend函数可以访问私有成员
        friend void goodFriend(Building &build); //全局函数做友元
    public:
        string m_SittingRoom;   //客厅
        Building();
    private:
        string m_BedRoom;   //卧室
    
    };
    
    Building::Building()
    {
        m_SittingRoom = "客厅";
        m_BedRoom = "卧室";
    }
    
    //全局函数
    void goodFriend(Building &build)
    {
        cout << "好朋友正在访问: " << build.m_SittingRoom << endl;
        cout << "好朋友正在访问: " << build.m_BedRoom << endl; 
    }
    

    2. 类做友元

    class Building
    {
        //GoodFriend类做友元
        friend class GoodFriend;
    public:
        string m_SittingRoom;   //客厅
        Building();
    private:
        string m_BedRoom;   //卧室
    
    };
    Building::Building()
    {
        m_SittingRoom = "客厅";
        m_BedRoom = "卧室";
    }
    ////////////////////////////////////////////////
    class GoodFriend
    {
    public:
        GoodFriend();
        Building * building;
        void visit(); //访问building中的属性
    
    private:
    
    };
    GoodFriend::GoodFriend()
    {
        //创建建筑物对象
        building = new Building;
    }
    ////////////////////////////////////////////////
    void GoodFriend::visit()
    {
        cout << "好朋友类正在访问: " << this->building->m_SittingRoom << endl;
        cout << "好朋友类正在访问: " << this->building->m_BedRoom << endl;
    }
    

    3. 成员函数做友元

    class Building;
    
    class GoodFriend
    {
    public:
        GoodFriend();
        void visit(); //访问building中的属性
        Building * building;
        
    };
    
    class Building
    {
        //GoodFriend::visit()成员函数做友元
        friend void GoodFriend::visit();
    public:
        string m_SittingRoom;   //客厅
        Building();
    private:
        string m_BedRoom;   //卧室
    
    };
    
    GoodFriend::GoodFriend()//注意构造函数的位置,用到了Building类,再Building之后再实现
    {
        //创建建筑物对象
        building = new Building;  
    }
    Building::Building()
    {
        m_SittingRoom = "客厅";
        m_BedRoom = "卧室";
    }
    void GoodFriend::visit()
    {
        cout << "好朋友类正在访问: " << this->building->m_SittingRoom << endl;
        cout << "好朋友类正在访问: " << this->building->m_BedRoom << endl;
    }
    void test()
    {
        GoodFriend f1;
        f1.visit();
    }
    

    相关文章

      网友评论

          本文标题:友元

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