gpt4 book ai didi

c++ - 将基类对象转换为派生类

转载 作者:行者123 更新时间:2023-11-28 07:20:36 24 4
gpt4 key购买 nike

假设我有两个类,像这样的动物和狗。

class Animal
{

};

class Dog : public Animal
{

};

我有一个名为 animal 的动物对象,它实际上是 dog 的一个实例,我如何将它转换回 dog?这似乎是一个奇怪的问题,但我需要它,因为我正在编写一个编程语言解释器,并且在堆栈上所有内容都存储为 BaseObject,而所有其他数据类型都扩展了 BaseObject。我如何将基础对象从堆栈转换为特定的数据类型?我试过这样的事情

Dog dog = static_cast<Dog>(animal);

但它给了我一个错误

1>------ Build started: Project: StackTests, Configuration: Debug Win32 ------
1> StackTests.cpp
1>c:\users\owner\documents\visual studio 2012\projects\stacktests\stacktests\stacktests.cpp(173): error C2440: 'static_cast' : cannot convert from 'Animal' to 'Dog'
1> No constructor could take the source type, or constructor overload resolution was ambiguous
1>c:\users\owner\documents\visual studio 2012\projects\stacktests\stacktests\stacktests.cpp(173): error C2512: 'Dog' : no appropriate default constructor available
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

编辑:我决定改用指针。

最佳答案

使用 dynamic_cast:

Animal& animal = getAnimalFromStack();    
if(Dog *d = dynamic_cast<Dog*>(&animal))
{
// You have a dog pointer, use *d ...

}

关于c++ - 将基类对象转换为派生类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19528901/

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