C++是否有可能使一个类扩展一个类并同时成为一个接口的实现?
您能提供一个简单的代码示例吗? (对不起,C++ nube)以及如何从您正在扩展的类中调用函数?
Coluld you provide a simple code example? (sorry C++ nube) and how to call a function from the class you are extending?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
一个有用的例子::-)
A bit useful example: :-)
在C++中,你可以扩展多个类,这称为多重继承。这很可能就是您正在寻找的。请阅读一本关于多重继承和 C++ 的好书(快速介绍:http://publib.boulder.ibm.com/infocenter/comphelp/v8v101/index.jsp?topic=%2Fcom.ibm.xlcpp8a.doc% 2Flanguage%2Fref%2Fcplr134.htm),因为有很多陷阱和细节需要注意。
多重继承的示例:
In C++, you can extend multiple classes, it's called multiple inheritance. Most probably this is what you're looking for. Please read a good book about multiple inheritance and C++ (a quick introduction: http://publib.boulder.ibm.com/infocenter/comphelp/v8v101/index.jsp?topic=%2Fcom.ibm.xlcpp8a.doc%2Flanguage%2Fref%2Fcplr134.htm), because there are many pitfalls and details to pay attention to.
Example for multiple inheritance:
C++ 没有显式地具有接口,相当于 Java 中的接口通常使用仅具有纯虚函数(加上构造函数、析构函数、复制赋值)的类来实现:
C++ doesn't explicitly have interfaces, the equivalent of an interface in Java is usually implemented with a class having only pure virtual functions (plus constructors, destructor, copy assignment):
不确定您在问什么:
请注意,多重继承可能会导致真正难以解决的问题,我建议仅在必要时使用它。
Not sure what you're asking:
Note that multiple inheritance can lead to really hard-to-solve problems and I would recommend to only use it when necessary.
如所提出的问题,
没有多大意义。答案就是“是”。您可以从任意数量的类派生:C++ 完全支持多重继承。
因此,鉴于所提出的问题并没有真正的意义,您至少有可能想要问
这个问题的答案也是肯定的,但这并不是微不足道的。它涉及虚拟继承。这是相当棘手的。
下面是一个示例:
虚拟继承确保在
MyClass
实例中只有 一个 类型为TalkerInterface
的子对象。这会产生一些违反直觉的后果。一是“在实现中继承”有效,二是基类子对象的构造发生在每个MyClass
构造函数中,更一般地发生在最派生的类中。干杯&呵呵,
The question as stated,
does not make much sense. The answer to that is just "yes". You can derive from any number of classes: C++ fully support multiple inheritance.
So, given that the question as stated isn't really meaningful, it's at least possible that you meant to ask
The answer to this question is also yes, but it's not trivial. It involves virtual inheritance. Which is quite tricky.
Here's an example:
The virtual inheritance ensures that there is only one sub-object of type
TalkerInterface
in aMyClass
instance. This has some counter-intuitive consequences. One is that "inheriting in an implementation" works, and another is that construction of that base class sub-object happens down in eachMyClass
constructor, and more generally down in the most derived class.Cheers & hth.,