在C ++中,是一个函数自动虚拟,如果它覆盖一个虚函数? [英] In C++, is a function automatically virtual if it overrides a virtual function?

查看:99
本文介绍了在C ++中,是一个函数自动虚拟,如果它覆盖一个虚函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望如果 foo 在类 D 中声明但未标记为virtual,将调用 D 中的 foo 的实现(不考虑 d )。

I would expect that if foo is declared in class D, but not marked virtual, then the following code would call the implementation of foo in D (regardless of the dynamic type of d).

D& d = ...;
d.foo();

但是,在以下程序中不是这样。任何人都可以解释这个?如果一个方法覆盖了一个虚拟函数,它是否会自动虚拟?

However, in the following program, that is not the case. Can anyone explain this? Is a method automatically virtual if it overrides a virtual function?

#include <iostream>

using namespace std;

class C {
public:
        virtual void foo() { cout << "C" << endl; }
};

class D : public C {
public:
        void foo() { cout << "D" << endl; }
};

class E : public D {
public:
        void foo() { cout << "E" << endl; }
};

int main(int argc, char **argv)
{
        E& e = *new E;
        D& d = *static_cast<D*>(&e);
        d.foo();
        return 0;
}

上述程序的输出是:

E


推荐答案

标准10.3.2(class.virtual)说:

Standard 10.3.2 (class.virtual) says:


如果在类中声明虚拟成员函数vf Base和类Derived中,直接或间接从Base派生出一个与Base :: vf具有相同名称和相同参数列表的成员函数vf,那么Derived :: vf也是virtual(无论它是如此声明的)并覆盖*

If a virtual member function vf is declared in a class Base and in a class Derived, derived directly or indirectly from Base, a member function vf with the same name and same parameter list as Base::vf is declared, then Derived::vf is also virtual (whether or not it is so declared) and it overrides*

[脚注:具有相同名称但不同参数列表(子句覆盖)作为虚函数的函数不一定是虚函数, 。在覆盖函数的声明中使用虚拟说明符是合法的,但是是冗余的(具有空语义)。在确定覆盖时不考虑访问控制(子句类。访问)。 --- end foonote]

[Footnote: A function with the same name but a different parameter list (clause over) as a virtual function is not necessarily virtual and does not override. The use of the virtual specifier in the declaration of an overriding function is legal but redundant (has empty semantics). Access control (clause class.access) is not considered in determining overriding. --- end foonote]

这篇关于在C ++中,是一个函数自动虚拟,如果它覆盖一个虚函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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