我使用三种不同的编译器来编译这段代码。其中之一(我最不信任的那个)警告说,Derived 中的函数隐藏了 Base 中的函数。其他编译器(一个是 Visual C++ )不会发出警告。如果我启用/Wall 或/W4,Visual C++ 甚至不会给出警告。
我倾向于认为这是编译器中发出警告的错误,因为它会编译代码。如果它确实没有覆盖基本函数,那么当我创建派生模板的实例时它应该会出错。
谁能确认这应该如何表现?
struct Base
{
virtual void Func(float f) = 0;
};
template <typename T>
struct Derived : Base
{
virtual void Func(T f){}
};
int main()
{
Derived<float> d;
d.Func(0);
return 0;
}
当 Derived
用 float
实例化时,我收到意外警告。当 Derived
用 int
实例化时,我得到一个错误,正如预期的那样。
最佳答案
它确实被覆盖了。您可以在 C++11 中使用 override
关键字轻松说服自己,如果函数未被覆盖,则不允许代码编译:
struct Base
{
virtual void Func(float f) = 0;
virtual ~Base() = default; // to silence warnings
};
template <typename T>
struct Derived : Base
{
void Func(T f) override {} // will fail to compile if not overriding
};
int main()
{
Derived<float> d;
d.Func(0);
return 0;
}
实例here .
请注意,在 C++11 之前,您可能会通过更改派生类中的签名来意外隐藏 virtual
基函数,因此即使您标记派生函数 virtual
代码仍然可以编译,但不再是多态的,参见这样的示例 here .不幸的是 g++ 没有提供任何警告,即使是 -Wall -Wextra
。这就是为什么 override
是一种在编译时实际强制执行真正覆盖的更安全的方法。
关于c++ - 该函数是否覆盖了基本函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29614197/