简体   繁体   English

将基类对象转换为派生类

[英]Cast base class object to derived class

Lets say I have two classes, animal and dog like this. 可以说我有两个班,像这样的动物和狗。

class Animal
{

};

class Dog : public Animal
{

};

And I have an animal object named animal, that is actually an instance of dog, how would I cast it back to dog? 而且我有一个名为动物的动物对象,实际上是狗的一个实例,我该如何将其丢回给狗? This may seem like an odd question, but I need it because I am writing a programming language interpreter, and on the stack everything is stored as a BaseObject, and all the other datatypes extend BaseObject. 这似乎是一个奇怪的问题,但我需要它,因为我正在编写编程语言解释器,并且在堆栈上所有内容都存储为BaseObject,而所有其他数据类型都扩展了BaseObject。 How would I cast the base object from the stack, to a specific data type? 如何将基础对象从堆栈转换为特定的数据类型? I have tried something like this 我已经尝试过这样的事情

Dog dog = static_cast<Dog>(animal);

But it gives me an error 但这给我一个错误

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 ==========

Edit: I have decided to use pointers instead. 编辑:我决定改为使用指针。

Use dynamic_cast: 使用dynamic_cast:

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

    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM