首页 > 解决方案 > 派生类中的私有重写虚函数

问题描述

如果这些在基类中是公共的,那么从基类私有覆盖的虚拟成员函数是否有任何意义?

struct base {
    virtual void a();
};

struct derived : base {
// ...
private:
    void a() override;
};

标签: c++inheritancevirtual-functionsprivate-membersaccess-specifier

解决方案


查看您的设计,我发现无法derived::a直接调用,而只能通过base接口调用。

有什么意义吗?考虑一下,一旦我们有了一个derived实例,我们总是可以向上转换到它的基础,所以给定

derived d;

虽然d.a()不会编译,但我们总是可以做

base & b = d;
b.a(); //which actually calls derived::a

换句话说:毕竟derived::a不是那么私密,我不鼓励这种设计,这可能会让用户感到困惑。

如果成员 private inderived也是 private in base,情况就会发生变化:这一次很明显,它们不能直接在外部base或中调用derived

假设我们有几个函数,并希望根据作为参数传递给第三个函数的值有条件地调用它们:

struct base 
{
    void dosomething(bool x)
    {
        if(x)
        {
            do_this();
        }
        else
        {
            do_that();
        }
    }
private:
    virtual void do_this(){}
    virtual void do_that(){}
};

因此派生类可能是这样的:

struct derived : base 
{
private:
    void do_this() override { }
    void do_that() override { }
};

并且没有其他类可以调用它们,除非它扩展了base自己:

derived d;
d.dosomething(true); //will call do_this() in derived
d.dosomething(false); //will call do_that() in derived

d.do_that() //won't compile

推荐阅读