覆盖虚函数时的返回值(Return type of an overriding virtual member function)

来源:互联网 发布:第三方数据服务商 编辑:程序博客网 时间:2024/06/05 14:12
 

http://www.devx.com/tips/Tip/12476

Once declared virtual, a member function can be overridden in any level of derivation, as long as the overriding version has the identical signature of the original declaration. This is quite straightforward, but sometimes a virtual has to return an object of type that differs from the return type declared in its base class. The C++ Standard allows that only when the return type is replaced with a class publicly derived from the original return type. For example:

class B {
 virtual B* clone () const { return new B; }
}

class D {
 void* clone () const { return new B; } //error; return type
      //differs

 D* clone () const { return new D; } //OK, D is publicly
        //derived from B

}

原创粉丝点击