C++ 使用不同的返回类型覆盖虚拟函数

C++ Overriding virtual function with different return type

本文关键字:返回类型 覆盖 虚拟 函数 C++      更新时间:2023-10-16

我刚才很惊讶地看到这段代码(释义(构建了。

class Foo
{
protected:
virtual bool CheckThis(int id);
}
class Bar : public Foo
{
protected:
virtual tErrorCode CheckThis(int id, char something);
};

我认为不可能用不同的返回类型覆盖函数?不知何故,这建立了。操作系统是vxworks。

事实上,这种方法:

virtual tErrorCode CheckThis(int id, char something);

不覆盖任何内容,因为它与此方法具有不同的签名:

virtual bool CheckThis(int id);

请注意,您可以使用override说明符来确保派生类中的方法实际重写基类的方法。

所以,这段代码:

class Foo {
protected:
virtual bool CheckThis(int id);
};
class Bar : public Foo
{
protected:
virtual tErrorCode CheckThis(int id, char something) override;
};

不会编译,但这个会:

class Foo {
protected:
virtual bool CheckThis(int id);
};
class Bar : public Foo
{
protected:
virtual bool CheckThis(int id) override;
};

我认为不可能用不同的返回类型覆盖函数?

是的,这是可能的,但有一些限制。

特别是,您不能使用所需的任何类型,只能使用协变类型。

此外,参数类型必须相同,否则它不是重写。

例:

class type1 {};
class type2 : public type1 {};
class Foo {
protected:
virtual type1& CheckThis(int id);
}
class Bar : public Foo
{
protected:
// This is not an override, it is an overload.
virtual type2& CheckThis(int id, char);
// This is an override.
virtual type2& CheckThis(int id);
};

从 C++11 开始,您应该使用特殊的override关键字。它允许编译器检查基类是否具有派生类重写的方法。

现场示例

class Foo 
{
protected:
virtual bool CheckThis(int id);
}
class Bar : public Foo
{
protected:
tErrorCode CheckThis(int id, char something) override; // error:  marked 'override', but does not override
};

此外,由于重写基类方法,因此派生类中不需要virtual关键字。 基方法是virtual的,所以覆盖方法是隐式virtual的。