gpt4 book ai didi

c++ - 为什么编译器提示不能用 Base 类型的右值初始化 "Derived"

转载 作者:行者123 更新时间:2023-11-30 01:13:06 27 4
gpt4 key购买 nike

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()

但我已经将克隆虚拟并让Derived 中的clone() 返回Derived *

为什么我还有这样的问题?

最佳答案

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

关于c++ - 为什么编译器提示不能用 Base 类型的右值初始化 "Derived",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32814576/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com