这给人一种完全新手问题的感觉,但是为什么当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++ 打印以下错误消息:
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
-关键字是多余的(而我认为省略它会阻止继承)。但是,我问这个问题的目标 - 即整个动态和静态继承层次结构中的一致接口 - 可以通过在整个过程中使用非虚拟operator[]
来解决,并通过虚拟函数apply
A
和B
的类耦合:
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()()
成为非虚拟的。
生类中的函数与基类中的虚函数具有相同的签名,将覆盖基类中的该虚函数。这使它成为一个虚函数,即使/尽管派生类中的声明不使用 virtual
关键字。
这是无法更改的,因此,如果您确实需要在派生类中具有相同名称的函数,该函数不会覆盖基类中的虚函数(并且在此过程中,成为虚拟本身,在这种情况下,违反了B
中的final
),则需要更改派生类中函数的签名。这可能意味着不同的名称、不同的参数列表或不同的限定符。不过,我会非常谨慎地对待后两者 - 编译器将能够整理出你造成的混乱,但许多人类读者可能会(很容易)感到惊讶。
如果我正在审查这样的代码,我可能会认为这是一个问题,作者需要提供非常坚实的理由来说明为什么真正有必要获得批准。
作为重写(因为它与基类中的虚拟函数具有相同的签名),重写与其基类中指定的final
冲突。
一种解决方法(或者更确切地说是解决方法)是给该函数一个默认参数,以便它具有不同的类型,因此不是覆盖,更好的方法是修复设计。