也没有在派生类中定义虚拟方法 [英] Not defining Virtual method in derived class as well
问题描述
我具有以下类层次结构.
I have the following class hierarchy.
class A {
public:
virtual bool foo() const;
};
class B : public A {
// Redeclare foo as virtual here?
};
class C : public B {
bool foo() const {/*Definition*/ return true;}
};
class D : public B {
bool foo() const {/*Definition*/ return false;}
};
因此,类C和D想要实现的foo()方法,而B则没有.我该如何实现?我是否必须在B类中将foo()重新声明为虚拟的?
So the foo() method the class C and D wants to implement, B doesn't. How can I achieve that? Do I have to re-declare the foo() as virtual in class B?
注意:忽略此处的小句法错误.这不是实际的代码.我的问题只是关于这个概念.
Note: Ignore minor syntactical error here and there. This is not actual code. My question is only about the concept.
推荐答案
-
如果严格希望派生类实现函数,则在基类中将函数设为
pure virtual function
.如果只想让随机派生类重新使用一个函数,则只需在基类中创建函数
virtual
,就像您在示例中所做的那样.If you just want random derived class to reimplment a function then simply make the function
virtual
in the base class, which you did in your example.现在,由于函数
foo
在基础class A
中为virtual
,因此将为class A
创建虚拟表vtable
,并且直接或间接地从class A
派生所有类.Now, since function
foo
isvirtual
in baseclass A
so a virtual tablevtable
will be create forclass A
and all the classes derived directly or indirectly fromclass A
.虚拟功能条目存储在
vtable
中,如果在后续派生类中重新实现它们,它们将仅在vtable
中被替换.Virtual Function entry are stored in
vtable
and they just get replaced invtable
if they are reimplemented in the subsequent derived classes.- 因此,如果
class B
重新实现foo
,则在class B
的vtable
中,条目将为B::foo
. - 因此,如果
class C
重新实现foo
,则在class C
的vtable
中,条目将为C::foo
.
- So, if
class B
reimplementsfoo
then invtable
ofclass B
the entry will beB::foo
. - So, if
class C
reimplementsfoo
then invtable
ofclass C
the entry will beC::foo
.
因此,不需要
class B
即可将函数foo
声明为virtual
.So,
class B
is not required to declare functionfoo
asvirtual
.如果函数是
virtual
,则将在运行时使用使用其对象的相应类的vtable
进行解析.If a function is
virtual
then resolution will happen at run time using thevtable
of the corresponding class whose object is used.这篇关于也没有在派生类中定义虚拟方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
- 因此,如果