2013-05-16 55 views
1

我有下一個類:陣列存儲器分配不起作用

int main() { 
    A* vec; // A is a class with pure virtual functions 
    vec = new B[2]; // want to create a vector of B 
} 

VEC [0]被正確地定義,但是VEC [1]爲:

class A { 
}; 

class B : public A { 
    int num; 
}; 
在我的主要我有

空值。爲什麼它沒有給我一個合適的記憶?

我不想改變主線。只是讓它工作。

(我知道我可以改變主要爲:B * VEC =新的B [2],但我不希望)

任何幫助表示讚賞!

+2

重複http://stackoverflow.com/questions/4973221/problem-allocating-derived-class-array-with -new – bjskishore123

回答

5

你不能多態地處理數組,C++語言不支持它。表達式vec[x]使用指針算術來確定元素的位置。如果您通過基類指針訪問它,如果對象的大小以任何方式變化,它將不起作用。

例如,您的基類大小爲4個字節,子類大小爲8個字節。

base *a = new child[4]; 

當您訪問a[1]編譯器計算使用基類大小的偏移。在這種情況下,偏移量是4個字節,最終指向第一個元素的中間。

我推薦使用指針的std::vectorstd::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()); 
} 
+0

你的意思是''不支持它',對吧? – Paul

+0

@paul對;)謝謝。 –

+0

難道你不能只做B * vec_cp = new B [2]; memcpy(vec,vec_cp,sizeof(vec_cp))?通過直接在內存上操作,您可以繞過IMO的這一限制。 – lucasg

0

此代碼片段說明您遇到的問題。

#include <iostream> 
using namespace std; 
class A { 
}; 

class B : public A { 
    int num; 
}; 

int main() { 
    A* vec; // A is a class with pure virtual functions 
    vec = new B[2]; // want to create a vector of B 

    cout << sizeof(vec) << endl; 
    cout << sizeof(*vec) << endl; 
    cout << sizeof(vec[2]) << endl; 
    cout << sizeof(new B()) << endl; 
} 

在指針arrithmetic,你分配的指針類型的大小是什麼是用於遞增,不是真正的類型,它指向的對象的大小。更簡單地說,該語言不支持多態數組。這只是對原因的解釋。

1

,如果你想它是多態的只是創建一個指針數組

new A*[array_size]