在C++中防止虚拟方法实现

Jam*_*son 4 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
    }
};
Run Code Online (Sandbox Code Playgroud)

我想保证实现级别的类不提供自己的apply实现,并且它们只实现derived_specialty.有没有办法保证继承自Derived的类不会实现apply,以便使用Derived :: apply实现?我的理解是,在C++中,在Base类中创建虚拟的方法在继承层次结构中一直是虚拟的,但是如果C++中有任何技巧要完成,我会有兴趣听到它们.

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

use*_*714 21

您可以使实现成为委托类而不是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(){}
};
Run Code Online (Sandbox Code Playgroud)

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


Chr*_*isW 5

你可以通过组合来做到这一点:

class Base {
    virtual void apply();
};

class Derived : public Base {

    class IImplementation {
        virtual void derived_specialty() = 0;
    };

    IImplementation& m_implementation;

    Derived(IImplementation& implementation)
        : m_implementation(implementation)
    {}

    virtual void apply() {
        // implementation here that uses m_implementation.derived_specialty
    }

};


class Implementation : Derived::IImplementation {   
    virtual void derived_specialty() {
        // implementation
    }
};
Run Code Online (Sandbox Code Playgroud)

其他类仍然可以继承Derived并覆盖apply方法,但您的Implementation类不再是这些类中的一个.


小智 5

在文档中明确限制.


小智 5

"我想保证实施层面的课程不提供自己的申请实施."

你不能.

到目前为止,我见过的所有示例都没有阻止任何派生类定义自己的apply函数.它们都提供了对apply和derived_specialty之间关系建模的方法,建议用户不要覆盖apply.但是,您可以在一系列文档中实现相同的目标.

您正在寻找的是C++中不存在的Java final语句,对吧?