C++ 虚拟 class 方法

C++ virtual class method

假设我在 C++ 中有一个超级 class A,它有一个虚拟方法。如果我想在我的 class B 上覆盖它并仍然保持虚拟,建议将 virtual 关键字保留在 class B 上吗?我可以忽略它吗,因为我已经说过该方法是虚拟的超级 class?

例如,执行以下操作的正确方法是什么。

方法一:

class A{ 
    public:
        virtual void hello(){
            std::cout << "Hello World!" << std::endl;
        };
};
class B: public A{
    public:
        virtual void hello() override{
            std::cout << "Hello Sun!" << std::endl;
        };

};
class C: public B{
    public:
        virtual void hello() override{
            std::cout << "Hello Moon!" << std::endl;
        };

};

或者仅在第一个 class 上将函数声明为虚拟函数。

方法二:

class A{ 
    public:
        virtual void hello(){
            std::cout << "Hello World!" << std::endl;
        };
};
class B: public A{
    public:
        void hello() override{
            std::cout << "Hello Sun!" << std::endl;
        };

};
class C: public B{
    public:
        void hello() override{
            std::cout << "Hello Moon!" << std::endl;
        };

}; 

我想在所有情况下都使用延迟出价。所以我需要 hello() 方法在三个 classes 中是虚拟的。这两种方法都适用于 CodeBlocks,但我不知道什么是最好的方法,即使它们之间有任何区别。

virtual对于BC来说是多余的,效果是完全一样的。重要的是,如果要覆盖虚拟方法,请始终使用 override1 标记您的方法。虽然这不是绝对必要的,但这是一个很好的做法。你在这两个例子中都做对了。

相关标准语:

n4140

§ 10.3 [class.virtual] / 2

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, parameter-type-list, cv-qualification, and refqualifier (or absence of same) as Base::vf is declared, then Derived::vf is also virtual (whether or not it is so declared) and it overrides Base::vf.


1 override 作为说明符自 C++11 起可用。