gpt4 book ai didi

c++ - 多态性 : Compliation Error in the code. 需要解释

转载 作者:行者123 更新时间:2023-11-30 02:56:54 26 4
gpt4 key购买 nike

以下代码给出了编译错误:第 1 行中的“无法从‘Cloneable*’转换为‘AClass*’”。据我所知,它涉及编译时和运行时多态性的概念。但我对此没有具体的推理。请帮忙。

struct Cloneable
{
virtual Cloneable* clone()
{
cout << "Cloneable";
return new Cloneable;
}

virtual ~Cloneable() {}
};


struct AClass : public Cloneable
{
virtual AClass* clone()
{
cout << "AClass";
return new AClass;
}
};

int main()
{
Cloneable* s1 = new AClass;
AClass* s2 = s1->clone(); //Line 1
return 0;
}

最佳答案

基本上,当您将新的 AClass* 存储在基类指针中时,调用 clone 的结果将是一个 Cloneable*,它需要向下转换为 AClass*,这可能并不总是安全的。因此编译器需要一个dynamic_cast ()

关于c++ - 多态性 : Compliation Error in the code. 需要解释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15120274/

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