class Base
{
public :
void func()
{
cout << "Base func()" << endl;
}
};
class DerivedA : public Base
{
public :
void func()
{
cout << "Derived A func()" << endl;
}
};
class DerivedB : public Base
{
public :
void func()
{
cout << "Derived B func()" << endl;
}
};
void main()
{
DerivedA a;
DerivedB b;
vector<shared_ptr<Base>> temp;
temp.push_back(make_shared<DerivedA> (a));
temp.push_back(make_shared<DerivedB> (b));
for(auto ptr : temp)
ptr->func();
}
输出是
Base func()
Base func()
但我所期望的是
Derived A func()
Derived B func()
如何在不切片的情况下将派生类推入基类向量?如果没有办法解决这个问题,是否有任何等效的方法可以将多个派生类存储到一个类似对象的数组中?