考虑以下示例。
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
成为 friend :
class A
{
int member;
friend /*class*/ B; // class is optional, required if B isn't declared yet
};
请注意,friend
是反模式 - 如果某些内容是 private
,则可能不应访问它。你想达到什么目的?为什么 A 不是独立的?为什么另一个类需要访问它的内部数据?
如果您对这些问题有有效的答案/原因,请使用 friend 。
关于c++如何正确声明另一个类的友元类方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32561001/