为什么允许覆盖非虚函数?

ste*_*lla 1 c++ virtual function

我正在使用C++进行继承.

struct A {
    virtual void foo(){ std::cout << "foo()" << std::endl; }
    void bar(){ std::cout << "bar()" << std::endl; }
};

struct B : A{
    void foo(){ std::cout << "derived foo()" << std::endl; }
    void bar(){ std::cout << "derived bar()" << std::endl; }
};

struct C : B {
    void foo(){ std::cout << "derived derived foo()" << std::endl; }
    void bar(){ std::cout << "derived derived bar()" << std::endl; }
};

int main()
{

    B* b = new C();
    b->foo();  //derived derived foo()
    b->bar();  //derived bar()
}
Run Code Online (Sandbox Code Playgroud)

现场演示

因为,foostruct B我预期的函数中被声明为非虚B函数的函数将被调用.但是foo哪一个C是.为什么?我改变了函数的"虚拟状态" B.为什么它仍然是虚拟的?

son*_*yao 5

foo()在基类中声明为虚函数A,因此foo()在所有派生类中也将是虚拟的.

从标准,10.3 $ 2虚函数[class.virtual](由我粗体)

如果虚拟成员函数vf在类Base和Derived类中声明,直接或间接从Base派生,则具有相同名称的成员函数vf,parameter-type-list(8.3.5),cv-qualification和声明了Base :: vf的ref-qualifier(或不存在相同的),然后Derived :: vf也是虚拟的(无论是否如此 声明)并且它覆盖Base :: vf.