【问题标题】:why compiler complains cannot initialize "Derived" with an rvalue of type Base为什么编译器抱怨无法使用 Base 类型的右值初始化“派生”
【发布时间】: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


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-13
    • 1970-01-01
    • 1970-01-01
    • 2011-01-22
    • 2011-07-23
    相关资源
    最近更新 更多