c++ - 防止在 C++ 中实现虚方法

标签 c++ inheritance encapsulation

我在 C++ 中有以下类层次结构:

class Base {
    virtual void apply() = 0;
};

class Derived : public Base {
    virtual void apply() {
        // implementation here that uses derived_specialty
    }

    virtual void derived_specialty() = 0;
};


class Implementation : public Derived {   
    virtual void derived_specialty() {
        // implementation
    }
};

我想保证实现级别的类不提供它们自己的 apply 实现,它们只实现 derived_specialty。有没有办法保证继承自 Derived 的类不会实现 apply,从而使用 Derived::apply 实现?我的理解是,在 C++ 中,基类中的虚拟方法在继承层次结构中一直是虚拟的,但如果 C++ 中有任何技巧可以实现,我很想听听它们。

我总是对 C++ 允许的事情感到惊讶,所以我认为值得一问。 :)

最佳答案

您可以使 Implementation 成为委托(delegate)类而不是 Derived 的特化

class Derived : public Base
{
    Derived()

    void apply() 
    {
        //whatever, delegate to impl class instance
        impl->apply_specialization();
    }


    Impl* impl;
};

class Impl : public WhateverImplInterface
{
      void apply_specialization(){}
};

然后实现无法访问 apply 函数并与层次结构分离。 Derived 类然后由 Impl 类的实例参数化。

关于c++ - 防止在 C++ 中实现虚方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/549849/

相关文章:

c++ - 断言加载文件失败

c++ - child 的构造函数无法识别基类的成员 : mean, sigma "is not a nonstatic data member or base class"

c++ - 防止破坏封装

sql - 是否可以在 Firebird 中创建私有(private)存储过程?

c++ - 信息隐藏VS封装

c++ - 在 OS X Mavericks 中从 C++ 链接 C

今天的 C++ 多线程与 C++ 11 的流动情况 - 书籍建议

c++ - 在每个逗号分隔的对象上执行成员函数

Java继承...困惑

ios - 子类上无继承导出