如何在 C 中公开成员对象接口
C++:我有一个基本对象(对象 A),其中包含一个成员对象(对象 B)。成员对象接口(对象 B)需要通过指向对象 A 的指针完全公开。执行此操作的最佳方法是什么?我可以将该对象放置为公共成员,但这感觉就像是黑客攻击。我可以为 A 中的所有 B 接口编写包装器,但这感觉很丑。我可以合并对象,但我正在对 XML 进行类序列化,因此拥有不同的类会更干净。我考虑过朋友分类,但我认为这不适用于这种情况。
解决此类问题的标准方法是什么?
C++ : I have a basic object (object A) that contains a member object (object B). The member object interface (object B) needs to be fully exposed through the pointer to object A. What's the best way to do this? I could place the object as a public member but this feels like a hack. I could write wrappers for all B's interface in A but this feels ugly. I could merge the objects but I am doing class serialization to XML so having distinct classes is cleaner. I thought about friend classing but I don't think that applies to this situation.
What is the standard way to resolve this type of issue?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
让
B
实现一个接口IB
。A
在内部管理B
的实例,并有一个 gettergetB
,它返回私有IB
接口>B 实例。如果要保护B
实例,可以将IB
方法设置为const
并隐藏析构函数(通过在中将其设为私有) >IB
)。(这只是为了提供一个想法。距离我上次接触 C++ 已经过去 3 年多了。我可能会犯一些明显的错误。)
Let
B
implement an interfaceIB
.A
manages an instance ofB
internally and has a gettergetB
that returns theIB
interface of the privateB
instance. If you want to protect theB
instance, you can make theIB
methodsconst
and also hide the destructor (by making it private inIB
).(This is just to give an idea. It's been 3+ years since I last touched C++. I could have made some blatant errors.)
我拒绝接受这样做是个好主意的想法,但我会让它成为公共成员。如果您不喜欢这样,您可以使用 getB() 方法。如果可能的话,我会让它返回一个 const 引用而不是普通引用。
I reject the notion that doing this at all is a good idea, but I would make it a public member. If you don't like that you can have a getB() method. If possible, I would make it return a const reference instead of a normal reference.
超载-> A 中的运算符和实现中返回 B 类型的指针变量。
但正如您所知,您将无法通过 A 的指针和 -> 访问 A 的成员。此外,它还存在使阅读过代码的人感到困惑的风险。
我的意思是这样的。
Overload the -> operator in A and in the implementation return the pointer variable of type B.
But as you know you will not be able to access A's members through A's pointer and ->. Also it has the risk of causing confusion who ever read the code.
I meant something like this.