派生类中非虚函数的 C++ 同名与 `final` 说明符冲突

标签 c++ templates inheritance c++14 crtp

感觉完全是菜鸟问题,但是为什么final说明符用于B::operator()时,下面的代码编译不通过?

struct A
{
    virtual void operator()() const = 0;
};

// the CRTP-component is not really necessary here
// but it possibly makes more sense in that it could be applied like this in reality
//
template<typename Derived>
struct B : A
{
    virtual void operator()() const override final
    {
        static_cast<Derived const&>(*this).operator()();
    }
};

struct C : B<C>
{
    void operator()() const
    {
        //do something
    }
};

int main()
{
    C()();
}

G++ 打印以下 error message :

main.cpp:17:14: error: virtual function 'virtual void C::operator()() const'
         void operator()() const
              ^
main.cpp:9:22: error: overriding final function 'void B<Derived>::operator()() const [with Derived = C]'
         virtual void operator()() const override final
                      ^

我会认为它的工作原理是因为非虚拟 C::operator() 没有覆盖其基类中的虚拟函数?我怎样才能使它起作用(——不更改 C::operator() 的名称)?


编辑:正如一些用户所指出的,答案很简单,派生类中的 virtual 关键字是多余的(而我认为将其保留会阻止从继承)。然而,我提出这个问题的目的——即贯穿动态和静态继承层次结构的一致接口(interface)——可以通过使用非虚拟operator[]来解决通过虚函数 apply 贯穿并耦合类 AB:

struct A
{
    void operator()() const
    {
        this->apply();
    }

protected:
    virtual void apply() const = 0;
};

template<typename Derived>
struct B : A
{
    void operator()() const
    {
        static_cast<Derived const&>(*this).operator()();
    }

protected:
    virtual void apply() const override final
    {
        this->operator()();
    }
};

struct C : B<C>
{
    void operator()() const
    {
        //do something
    }
};

int main()
{
    C()();
}

最佳答案

如果一个函数在基类中声明为virtual,那么在派生类中用相同名称和参数列表声明的函数隐式为virtual使用 virtual 关键字。您不能使 C::operator()() 成为非虚拟的。

关于派生类中非虚函数的 C++ 同名与 `final` 说明符冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29086791/

相关文章:

c++ - 将十进制转换为二进制的C++循环的逻辑是什么

c++ - 模板/命名空间交互

c++ - 如何强制派生类比较

c++ - 模板参数无效

c++ - 错误:从父类父类派生子类Son时基类未定义

android - 将 FILE* 转换为 ifstream C++、Android NDK

C++ OpenGL 程序 - 添加图标

c++ - 在一定时间后预测物体的位置

c++ - 具有必要副作用的静态初始化被优化掉

symfony - Twig - 如何有效地重用代码