协变返回类型(covariant return type)

thatdor / 2024-02-22 / 原文

协变返回类型(covariant return type)

C++ 中的协变返回类型(covariant return type)是指派生类(子类)中的虚函数返回类型可以是基类(父类)中虚函数返回类型的子类。这个特性使得在派生类中可以返回更具体的类型,而不违反了虚函数的约定。

在 C++11 中,如果派生类的虚函数覆盖基类的虚函数,并且派生类的返回类型是基类函数的返回类型的派生类型(或其引用/指针),则可以使用协变返回类型。

示例:

#include <iostream>

class Base {
public:
    virtual Base* clone() const {
        std::cout << "Base::clone()" << std::endl;
        return new Base(*this);
    }
};

class Derived : public Base {
public:
    // 使用协变返回类型,返回类型是 Base 的派生类型 Derived*
    virtual Derived* clone() const override {
        std::cout << "Derived::clone()" << std::endl;
        return new Derived(*this);
    }
};

int main() {
    Derived d;
    Base* ptr = &d;
    Base* newPtr = ptr->clone(); // 调用 Derived::clone()
    delete newPtr;
    return 0;
}

在这个示例中,Derived​ 类覆盖了 Base​ 类的 clone​ 函数,并使用了协变返回类型,返回类型是 Base​ 类的派生类型 Derived*​。这样可以确保在基类指针指向派生类对象时调用的是派生类中的函数,而不是基类中的函数。

image