【发布时间】:2015-09-28 01:25:14
【问题描述】:
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 *。
为什么我还有这样的问题?
【问题讨论】:
标签: c++ derived-class