我在 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/