如何将父类强制转换为子类

Myk*_*oft 24 c++

已经有一段时间了,因为我不得不编写C++代码而且我感觉有点愚蠢.我编写的代码与下面的代码类似,但不完全相同:

class Parent
{
    ...
};

class Child : public Parent
{
    ...
};

class Factory
{
    static Parent GetThing() { Child c; return c; }
};

int main()
{
    Parent p = Factory::GetThing();
    Child c1 = p; // Fails with "Cannot convert 'Parent' to 'Child'"
    Child c2 = (Child)p; // Fails with "Could not find a match for 'TCardReadMessage::TCardReadMessage(TCageMessage)'"
}
Run Code Online (Sandbox Code Playgroud)

我知道这应该很简单,但我不确定我做错了什么.

fre*_*low 24

Parent通过值返回的对象不能可能包含任何Child信息.你必须使用指针,最好是智能指针,所以你不必自己清理:

#include <memory>

class Factory
{
    // ...

public:

    static std::auto_ptr<Parent> GetThing()
    {
        return std::auto_ptr<Parent>(new Child());
    }
};

int main()
{
    std::auto_ptr<Parent> p = Factory::GetThing();
    if (Child* c = dynamic_cast<Child*>(p.get()))
    {
        // do Child specific stuff
    }
}
Run Code Online (Sandbox Code Playgroud)


par*_*ish 7

参考下面的代码片段:

Child* c = dynamic_cast<Child*>(parentObject);
Run Code Online (Sandbox Code Playgroud)

其中,parentObject是类型Parent*

确保“parentObject”实际上是“Child”类型,否则为未定义行为。

请参阅更多信息