c++如何正确声明友类的另一个类的方法
c++ how to properly declare friend class method of another class
考虑下面的例子:
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++;
}
};
相关文章:
- C++从另一个类访问公共静态向量的正确方法是什么
- 在他自己的方法中,有可能将一个对象取消引用到另一个对象吗
- 在另一个类视图中添加最多2个图表的正确方法是什么
- 检查哪个对象调用了另一个对象的对象方法
- 不能将方法返回的值用于另一个方法
- Qt将信号与另一个类方法连接
- C++ STD 函数运算符:有没有一种方法可以通过函数将一个向量映射到另一个向量上?
- 将一个类的方法指针存储到另一个类中
- 从另一个标头中的标头调用静态方法
- 无法"this"指针传递到另一个类并在 CPP 中调用该类的任何方法
- C++ |DLL / EXE - 如何从导出的类调用另一个类方法?
- 在销毁期间从另一个线程调用对象上调用方法是否未定义行为?
- 如果类"A"具有指向另一个类的指针,则"B" A 可以访问 B 类公共方法
- 如何在另一个类中使用类成员的正确方法?
- 重写另一个方法 [C++] 使用的超类回调函数
- 如何构造一个类型特征,可以判断一个类型的私有方法是否可以在另一个类型的构造函数中调用?
- 如何启用使用另一个类的静态方法的模板函数的自动推导,从而消除冗长的调用方代码
- 覆盖作为另一个类的好友的虚拟受保护方法
- 将vector<vector<double>>从x86平台中创建的一个进程发送到x64中构建的另一个进程的最快方法是什么
- 返回一个引用C++中另一个类对象的对象的有效方法