C++朋友班
只是想确保我已经正确理解了朋友们关于这段
class A
{
friend class B;
int valueOne;
int valueTwo;
public:
int GetValueOne(){ return valueOne; }
}
class B
{
public:
A friendlyData;
int GetValueTwo(){ return friendlyData.valueTwo; }
}
main()
{
B myObject;
myObject.friendlyData.GetValueOne(); // OK?
myObject.GetValueTwo(); // OK?
}
代码的内容,如果我们忽略缺少初始化,那么 main 中的两个函数就可以了,对吗?除了做一些时髦的事情之外,他们应该没有其他方法从这些类中获取数据......在这些类的外部,BA
没有可访问的数据,只有成员函数。
Just trying to make sure I have understood friends properly with this one
class A
{
friend class B;
int valueOne;
int valueTwo;
public:
int GetValueOne(){ return valueOne; }
}
class B
{
public:
A friendlyData;
int GetValueTwo(){ return friendlyData.valueTwo; }
}
main()
{
B myObject;
myObject.friendlyData.GetValueOne(); // OK?
myObject.GetValueTwo(); // OK?
}
In reference to that code about, if we ignore the lack of initialising, the two functions in main would OK right? And besides doing some funky stuff, their should be no other way to get the data from these classes... To the out side of these class, B.A
has no accessible data, just the member function.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,
main
中识别的两个调用都正常。它们涉及 3 个成员的访问:B::A
、B::GetValueTwo
和A::GetValueOne
。所有这些都具有公共可访问性并且不公开任何私有类型。因此它们可以在任何地方使用,包括main
。Yes the two identified calls in
main
are OK. They involve the access of 3 members:B::A
,B::GetValueTwo
andA::GetValueOne
. All of which havepublic
accessibility and expose no privae types. Hence they're usable from anywhere includingmain
.看起来很合理,因为两个 GetValueX 方法都是公共的,因此调用没有问题。对
GetValueTwo()
调用的调用利用了它的友谊。警告:友谊可能会破坏设计中的封装。
It looks reasonable as both of the
GetValueX
methods are public and so the calls are fine. The call toGetValueTwo()
call makes use of its friendship.Word of warning: friendship can break the encapsulation in your design.