你不能多態地處理數組,C++語言不支持它。表達式vec[x]
使用指針算術來確定元素的位置。如果您通過基類指針訪問它,如果對象的大小以任何方式變化,它將不起作用。
例如,您的基類大小爲4個字節,子類大小爲8個字節。
base *a = new child[4];
當您訪問a[1]
編譯器計算使用基類大小的偏移。在這種情況下,偏移量是4個字節,最終指向第一個元素的中間。
我推薦使用指針的std::vector
或std::array
以及適當的智能指針。
// For arrays that needs to be resized (requires delete for each new)
std::vector<A*> vec(5, NULL);
for(int i = 0; i < vec.size(); i++)
{
vec[i] = new B();
}
// for arrays that are fixed in size (requires delete for each new)
std::array<A*, 5> vec;
for(int i = 0; i < vec.size(); i++)
{
vec[i] = new B();
}
// for arrays that are fixed in size with smart pointers
// no delete needed
std::array<std::unique_ptr<A>, 5> vec;
for(int i = 0; i < vec.size(); i++)
{
vec[i].reset(new B());
}
重複http://stackoverflow.com/questions/4973221/problem-allocating-derived-class-array-with -new – bjskishore123