也没有在派生类中定义虚拟方法 [英] Not defining Virtual method in derived class as well

查看:85
本文介绍了也没有在派生类中定义虚拟方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有以下类层次结构.

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 is virtual in base class A so a virtual table vtable will be create for class A and all the classes derived directly or indirectly from class A.

    虚拟功能条目存储在vtable中,如果在后续派生类中重新实现它们,它们将仅在vtable中被替换.

    Virtual Function entry are stored in vtable and they just get replaced in vtable if they are reimplemented in the subsequent derived classes.

    • 因此,如果class B重新实现foo,则在class Bvtable中,条目将为B::foo.
    • 因此,如果class C重新实现foo,则在class Cvtable中,条目将为C::foo.
    • So, if class B reimplements foo then in vtable of class B the entry will be B::foo.
    • So, if class C reimplements foo then in vtable of class C the entry will be C::foo.

    因此,不需要class B即可将函数foo声明为virtual.

    So, class B is not required to declare function foo as virtual.

    如果函数是virtual,则将在运行时使用使用其对象的相应类的vtable进行解析.

    If a function is virtual then resolution will happen at run time using the vtable of the corresponding class whose object is used.

    这篇关于也没有在派生类中定义虚拟方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆