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 *
。
爲什麼我仍然有這樣的問題?
見http://stackoverflow.com/questions/4665117/c-virtual-function-return-type – Pixelchemist