C++虚函数返回类型

C++ virtual function return type(C++虚函数返回类型)

本文介绍了C++虚函数返回类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

继承的类是否可以实现具有不同返回类型的虚函数(不使用模板作为返回)?

Is it possible for an inherited class to implement a virtual function with a different return type (not using a template as return)?

推荐答案

在某些情况下,是的,只要返回类型为 ,派生类使用不同的返回类型覆盖虚函数是合法的与原始返回类型协变.例如,请考虑以下内容:

In some cases, yes, it is legal for a derived class to override a virtual function using a different return type as long as the return type is covariant with the original return type. For example, consider the following:

class Base {
public:
    virtual ~Base() {}

    virtual Base* clone() const = 0;
};

class Derived: public Base {
public:
    virtual Derived* clone() const {
        return new Derived(*this);
    }
};

这里,Base 定义了一个名为 clone 的纯虚函数,它返回一个 Base *.在派生实现中,使用 Derived * 的返回类型覆盖此虚函数.尽管返回类型与基类中的不同,但这是完全安全的,因为您可以随时编写

Here, Base defines a pure virtual function called clone that returns a Base *. In the derived implementation, this virtual function is overridden using a return type of Derived *. Although the return type is not the same as in the base, this is perfectly safe because any time you would write

Base* ptr = /* ... */
Base* clone = ptr->clone();

clone() 的调用将始终返回一个指向 Base 对象的指针,因为即使它返回一个 Derived*,这个指针可以隐式转换为 Base* 并且操作是明确定义的.

The call to clone() will always return a pointer to a Base object, since even if it returns a Derived*, this pointer is implicitly convertible to a Base* and the operation is well-defined.

更一般地说,函数的返回类型永远不会被视为其签名的一部分.只要返回类型是协变的,您就可以使用任何返回类型覆盖成员函数.

More generally, a function's return type is never considered part of its signature. You can override a member function with any return type as long as the return type is covariant.

这篇关于C++虚函数返回类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:C++虚函数返回类型

基础教程推荐