automatically convert list of pointers to derived class to list of pointers to base class

前端 未结 4 2067
無奈伤痛
無奈伤痛 2020-12-07 03:11

Lets say that I have a base and derived class, and a function that takes an stl vector of pointers to the base class:

class A { public: int x; };

class B :          


        
4条回答
  •  Happy的楠姐
    2020-12-07 03:46

    As @Science_Fiction said earlier, it makes more sense to have a vector that holds pointers to the basic type and insert pointers to both basic and derived types into it, but if you don't control the creation of these arrays, you can use templates:

    template 
    inline void foo(const vector& v)
    {
        for (vector::const_iterator it = v.begin(); it < v.end(); ++it)
        {
            A* a = (A*) *it;
            cout << a->x << endl;
        }
    }
    

提交回复
热议问题