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