我如何将家长班当成孩子班

我如何将家长班当成孩子班

本文介绍了我如何将家长班当成孩子班的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

自从我不得不编写C ++代码以来已经有一段时间了,我感到自己有点愚蠢.我编写的代码类似于以下代码,但不完全:

It's been a while since I have had to write C++ code and I'm feeling kind of stupid. I've written code that is similar to, but is not exactly, the code below:

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)'"
}

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

I know this is supposed to be simple but I'm not sure what I'm doing wrong.

推荐答案

由值返回的 Parent 对象不能可能包含任何 Child 信息.您必须使用指针,最好是智能指针,因此您不必自己清理:

A Parent object returned by value cannot possibly contain any Child information. You have to work with pointers, preferably smart pointers, so you don't have to clean up after yourself:

#include <memory>

class Factory
{
    // ...

public:

    static std::unique_ptr<Parent> GetThing()
    {
        return std::make_unique<Child>();
    }
};

int main()
{
    std::unique_ptr<Parent> p = Factory::GetThing();
    if (Child* c = dynamic_cast<Child*>(p.get()))
    {
        // do Child specific stuff
    }
}

这篇关于我如何将家长班当成孩子班的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 18:30