C++ 为什么编译器抱怨无法初始化";“派生”;使用类型为Base的右值

C++ 为什么编译器抱怨无法初始化";“派生”;使用类型为Base的右值,c++,derived-class,C++,Derived Class,我用最新版本的Xcode编译上面的代码,编译器抱怨 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()

我用最新版本的Xcode编译上面的代码,编译器抱怨

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;
}
派生*d2=b->clone()

但是我已经将克隆
设为虚拟的
,并让派生中的
clone()
返回
Derived*


为什么我仍然有这样的问题?

Base::clone()的返回类型是
Base*
,而不是
派生*
。由于您是通过
Base*
调用
clone()
,因此预期的返回值是
Base*

如果通过
派生*
调用
克隆()
,则可以使用
派生::克隆()
的返回类型

而且

Base*b=d;
派生*d2=动态_转换(b->clone());//好啊
而且

Base*b=d;
派生*d2=动态_转换(b)->克隆();//好啊

Base::clone()的返回类型是
Base*
,而不是
派生*
。由于您是通过
Base*
调用
clone()
,因此预期的返回值是
Base*

如果通过
派生*
调用
克隆()
,则可以使用
派生::克隆()
的返回类型

而且

Base*b=d;
派生*d2=动态_转换(b->clone());//好啊
而且

Base*b=d;
派生*d2=动态_转换(b)->克隆();//好啊
请参见
cannot initialize a variable of type "Derived*" with an rvalue of type "Base*"*
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