为什么编译器抱怨无法使用 Base 类型的右值初始化 "Derived"

why compiler complains cannot initialize "Derived" with an rvalue of type Base

class Base {
public:
    virtual Base* clone() const { return new Base(*this); }
    // ...
};
class Derived: public Base {
public:
    Derived* clone() const override { return new Derived(*this); }
    // ...
};
int main() {
    Derived *d = new Derived;
    Base *b = d;
    Derived *d2 = b->clone();
    delete d;
    delete d2;
}

我在最新版本的 Xcode 中编译以上代码,编译器报错

cannot initialize a variable of type "Derived*" with an rvalue of type "Base*"*

Derived *d2 = b->clone()

但我已经克隆了 virtual 并让 Derived clone() return Derived *.

为什么我还有这样的问题?

Base::clone() 的 return 类型是 Base*,不是 Derived*。由于您通过 Base* 调用 clone(),预期的 return 值为 Base*.

如果您通过 Derived* 调用 clone(),您将能够使用 Derived::clone() 的 return 类型。

Derived *d = new Derived;
Derived *d2 = d->clone();   // OK

此外,

Base *b = d;
Derived *d2 = dynamic_cast<Derived*>(b->clone());  // OK

此外,

Base *b = d;
Derived *d2 = dynamic_cast<Derived*>(b)->clone();  // OK