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()
返回Derived *
。
为什么我还有这样的问题?
答案 0 :(得分:6)
Base::clone()
的返回类型为Base*
,而不是Derived*
。由于您通过clone()
调用Base*
,因此预期回报值为Base*
。
如果您通过clone()
调用Derived*
,则可以使用Derived::clone()
的返回类型。
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