I am going to guess you didn't declare the relevant methods in Base
as virtual
. Try this:
struct Base
{
virtual void print(std::ostream& os) const { os << "Base"; }
virtual ~Base() {}
};
struct Derived1 : Base
{
void print(std::ostream& os) const { os << "Derived1"; }
};
ans so on. Note I have only used struct
here to save me typing public
a few times.
Here is a working example:
#include <vector>
int main()
{
Base b;
Derived1 d;
std::vector<const Base*> v{&b, &d};
for (auto it = v.cbegin(); it != v.cend(); ++it)
{
std::cout << *(*it) << std::endl;
}
}
Output:
Base
Derived1
You can see it in action here.
Edit Your code has undefined behaviour because you are storing pointers to temporaries:
Store a("aaaaaaa");
a.Add(Derived("abc", 5));
a.Add(Derived("def", 6));
This version works as expected:
Store a("aaaaaaa");
Derived d0("abc", 5);
Derived d1("def", 6);
a.Add(d0);
a.Add(d1);
Edit 2: from your comments:
Lets say Iam forced to use a.Add(Derived("abc", 5)); What can I do with it in my implementation?
You could make Add
a template:
template <typename T>
void Add(const T& elem)
{
vec.push_back(new T(elem));
}
or
template <typename T>
void Add(const T& elem)
{
vec_smart.push_back(std::make_shared(elem));
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…