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()
我怎麼能推派生類到基類無切片矢量? 如果沒有辦法解決這個問題,是否有任何等價的方法將多個派生類存儲到一個數組中,如對象?