Retrieve data from heterogeneous std::list

前端 未结 4 1808
孤城傲影
孤城傲影 2021-01-24 20:14

In the below code I am simply trying to experiment with a Heterogeneous std::list where I have stored three Derived class object in a list of type Base*. When retrieving data fr

4条回答
  •  梦谈多话
    2021-01-24 20:44

    Easiest way might be to define Base like so:

    class Base {
    public:
        virtual const std::string& getData() = 0;
    }
    

    And then have your various derived classes implement getData() as appropriate. That way, your output loop could just be:

    for (Base* b : l) {
        cout << b->getData();
    }
    

提交回复
热议问题