C++继承 - 为什么我的函数没有被使用?
我有一个 IBase
类,其中包含 virtual void CastData(){}
。它被用在另一个函数中。
我有另一个完全不相关的类 IC
virtual void CastData(){
for (FunctionIterator it(funcs.begin()); it != funcs.end(); ++it){
DataType dataCopy;
dataCopy = *dataElement;
(*it)(dataCopy);
}
}
现在我想创建一个新类,其中来自 C 的 CastData 将覆盖来自基类的 CastData。
所以我尝试类似的东西 IGraphElement 类:公共 IBase、公共 IC
所有功能都可以正确运行。所有 IC 功能均运行,但 IBase CastData 未被覆盖。
当您继承的类的虚拟函数覆盖您继承的另一个类的虚拟函数时,如何进行此类类型的覆盖?
I have a IBase
class with virtual void CastData(){}
in it. there it is used in another function.
I have another totally unrelated class IC
with
virtual void CastData(){
for (FunctionIterator it(funcs.begin()); it != funcs.end(); ++it){
DataType dataCopy;
dataCopy = *dataElement;
(*it)(dataCopy);
}
}
Now I want to create a new class where CastData from C will overrite CastData from base class.
So I try something like
class IGraphElement : public IBase, public IC
All functions from run correctly. and all IC functions run but IBase CastData was not overwritten.
How to do such types of overrites when virtual functions from class you inherit overrite virtual functions from another class you inherit?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
虚函数必须由派生类重写,而不是由另一个基类重写。也许在 IGraphElement 中提供一个重写来调用 IC 来完成工作。
virtual functions must be overriden by a derived class, not another base class. Perhaps provide an override in IGraphElement that calls into IC to do the work.
如果您想重写所有的CastData,那么您可能需要抽象一个接口,并使IC 和IBase 派生自同一接口。但正如您所指出的,IBase 和 IC 完全不相关的类,那么您不应该期望 IGraphElement 可以优雅地覆盖 IBase 和 IC 中的 CastData。
If you want to override the CastData for all, then you may needs to abstract an interface and make IC and IBase derive from the same interface. But as you point out, IBase and IC totally unrelated class, then you should not expect IGraphElement can override CastData in IBase and IC gracefully.