gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:52:33 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com