梁梦笙 2021-07-27 22:13 采纳率: 100%
浏览 31
已结题

C++ 类A的成员函数作类B的友元函数,怎么访问不了类B的私有成员?

#include<iostream>
#include<string>
using namespace std;
class Bulding
{
    friend void Goodgay::visit();
public:
    Bulding()
    {
        m_room = "正在访问客厅";
        b_room = "正在访问卧室";
    }
    
    string m_room;
private:

    string b_room;
};
class Goodgay
{
public:
    Goodgay();
    void visit();

    Bulding* bulding;
};
 Goodgay::Goodgay()
{
    bulding = new Bulding;
}
void Goodgay::visit()
{
    cout << bulding->m_room << endl;
    cout << bulding->b_room << endl;//显示不可访问
}
void test()
{
    Goodgay b;
    b.visit();
}

int main()
{
    test();

    return 0;
}

  • 写回答

1条回答 默认 最新

  • qfl_sdu 2021-07-27 22:39
    关注

    在friend void Goodgay::visit();这里的时候,编译器不识别Goodgay,所以报错,代码修改如下:
    如有帮助,请采纳一下,谢谢。

    #include<iostream>
    #include<string>
    using namespace std;
    
    class Bulding;
    class Goodgay
    {
    public:
        Goodgay();
        void visit();
        Bulding* bulding;
    };
    
    
    class Bulding
    {
        friend void Goodgay::visit();
    public:
        Bulding()
        {
            m_room = "正在访问客厅";
            b_room = "正在访问卧室";
        }
        string m_room;
    private:
        string b_room;
    };
    
    Goodgay::Goodgay()
    {
        bulding = new Bulding;
    }
    void Goodgay::visit()
    {
        cout << bulding->m_room << endl;
        cout << bulding->b_room << endl;//显示不可访问
    }
    void test()
    {
        Goodgay b;
        b.visit();
    }
    int main()
    {
        test();
        return 0;
    }
    
    
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 系统已结题 8月5日
  • 已采纳回答 7月28日
  • 创建了问题 7月27日