首页 文章

如果不需要动态多态,基类是否应该将方法声明为虚拟?

提问于
浏览
2

使用是否有优势:

struct Base
{
    virtual void foobar();
};

struct Derived : public Base
{
    virtual void foobar() override;
};

代替:

struct Base
{
    void foobar();
};

struct Derived : public Base
{
    void foobar();
};

什么时候不需要动态/运行时多态?如果是这样,为什么?

谢谢 .

1 回答

  • 3

    库/程序应该只支持有意义的东西,如果你不打算/你想禁止类 Derived 可能替代 Base 类型的对象,那么你根本不应该提供这种可能性 .

    使用 class Derived : public Base ,您可以提供多态性,如果您提供多态性,它应该表现得像预期的那样 . 提供一个与基类同名但不覆盖它的成员显然是不可预期的,并且在这样做时你应该有充分的理由和良好的文档 .

    如果您不想提供多态性,您可以继承 private 或者您可以撰写:

    class B {
    public:
        int foo() { return 0; };
    };
    
    class D1 : private B {
    public:
        int foo() { return B::foo() + 1; };
    };
    
    class D2 {
    public:
        int foo() { return b.foo() + 1; };
    private:
        B b;
    };
    
    int main() {
    
        // B *b = new D1;  // Error cannot cast to private base class B
    
        // B *b = new D2;  // D2 is not a subclass of B
    
    }
    

相关问题