list of polymorphic objects

后端 未结 3 831
星月不相逢
星月不相逢 2020-12-03 19:09

I have a particular scenario below. The code below should print \'say()\' function of B and C class and print \'B says..\' and \'C says...\' but it doesn\'t .Any ideas.. I a

3条回答
  •  青春惊慌失措
    2020-12-03 19:57

    Your problem is called slicing and you should check this question: Learning C++: polymorphism and slicing

    You should declare this list as a list of pointers to As:

    list listOfAs;
    

    and then insert these aB and aC pointers to it instead of creating copies of objects they are pointing to. The way you insert elements into list is wrong, you should rather use push_back function for inserting:

    B bObj; 
    C cObj;
    A *aB = &bObj;
    A *aC = &cObj;
    
    listOfAs.push_back(aB);
    listOfAs.push_back(aC);
    

    Then your loop could look like this:

    list::iterator it;
    for (it = listOfAs.begin(); it != listOfAs.end(); it++)
    {
        (*it)->say();
    }
    

    Output:

    B Sayssss....
    C Says
    

    Hope this helps.

提交回复
热议问题