c++如何正确声明友类的另一个类的方法

c++ how to properly declare friend class method of another class

本文关键字:方法 另一个 何正确 声明 c++      更新时间:2023-10-16

考虑下面的例子:

class A
{
    int member;
};
class B
{
    A& a_ref;
    void manipulate()
    {
        a_ref.member++;
    }
};

显然,B::manipulate不能访问a_ref。我想允许(仅)class B获得(引用)A::member。我知道有friend关键字,但我不知道如何正确使用它。我的意图是,我可以改变B::manipulate的实现成为这个

int& A::only_B_can_call_this() // become friend of B somehow
{
    return member;
}
void B::manipulate()
{
    a_ref.only_B_can_call_this()++;
}

B成为朋友:

class A
{
    int member;
    friend /*class*/ B;  // class is optional, required if B isn't declared yet
};

注意friend s是反模式-如果某些东西是private,它可能不应该被访问。你想要完成什么?为什么A不是独立的?为什么另一个类需要访问它的内部数据?

如果你对这些问题有合理的答案或理由,请使用friend

您只需将friend class <class_name>;添加到希望使其成员可访问的类中,其中<class_name>是您希望为其提供访问权限的类的名称。

class A
{
    friend class B; // allow class B to access private members of A
    int member;
};
class B
{
    A& a_ref;
    void manipulate()
    {
        a_ref.member++;
    }
};
相关文章: