How do I cast a parent class as the child class

后端 未结 8 1955
深忆病人
深忆病人 2020-12-29 19:46

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 b

8条回答
  •  时光取名叫无心
    2020-12-29 20:35

    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 
    
    class Factory
    {
        // ...
    
    public:
    
        static std::unique_ptr GetThing()
        {
            return std::make_unique();
        }
    };
    
    int main()
    {
        std::unique_ptr p = Factory::GetThing();
        if (Child* c = dynamic_cast(p.get()))
        {
            // do Child specific stuff
        }
    }
    

提交回复
热议问题