2015-09-28 45 views
0
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

見http://stackoverflow.com/questions/4665117/c-virtual-function-return-type – Pixelchemist

回答

5

返回類型Base::clone()Base*而不是Derived*。由於您通過Base*調用clone(),因此預期回報值爲Base*

如果您通過Derived*調用clone(),您將能夠使用返回類型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 
+0

非常感謝 – Sherwin

+0

@xlnwel,不客氣。 –

相關問題