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

J D*_*oe. 1 c++

我刚才很惊讶地看到这段代码(释义)已经建成了.

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

class Bar : public Foo
{
  protected:
     virtual tErrorCode CheckThis(int id, char something);
};
Run Code Online (Sandbox Code Playgroud)

我认为不可能覆盖具有不同返回类型的函数?不知何故,这建成.操作系统是vxworks.

Edg*_*jān 5

实际上,这种方法:

virtual tErrorCode CheckThis(int id, char something);
Run Code Online (Sandbox Code Playgroud)

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

virtual bool CheckThis(int id);
Run Code Online (Sandbox Code Playgroud)

请注意,您可以使用说明override符来确保派生类中的方法实际上覆盖基类的方法.

所以,这段代码:

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

class Bar : public Foo
{
  protected:
     virtual tErrorCode CheckThis(int id, char something) override;
};
Run Code Online (Sandbox Code Playgroud)

不会编译,但这个将:

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

class Bar : public Foo
{
  protected:
     virtual bool CheckThis(int id) override;
};
Run Code Online (Sandbox Code Playgroud)