2011-11-03 137 views
0

給出一個簡單的類MyClass與接受兩個int一個構造函數,我怎麼能初始化的MyClass一個數組?C++如何初始化對象的數組在堆中

我已經試過

MyClass *classes[2] = { new MyClass(1, 2), 
         new MyClass(1, 2) }; 

但這似乎並沒有工作。謝謝

+1

您發佈的代碼已編譯。 – Pubby

+0

雖然數組在堆棧上,但堆上有指針 –

+1

@MooingDuck:No:*指針*位於堆棧上,對象位於堆上。 –

回答

1

爲此使用std::allocator<MyClass>

std::allocator<MyClass> alloc; 
MyClass* ptr = alloc.allocate(2); //allocate 
for(int i=0; i<2; ++i) { 
    alloc.construct(ptr+i, MyClass(1, i)); //construct in C++03 
    //alloc.construct(ptr+i, 1, i); //construct in C++11 
} 

//use 

for(int i=0; i<2; ++i) { 
    alloc.destroy(ptr+i); //destruct 
} 
alloc.deallocate(ptr); //deallocate 

請注意,您不必構造所有分配的內容。

或者,更好的是,只需使用std::vector

[編輯] KerrekSB認爲這是簡單的:

MyClass** ptr = new MyClass*[3]; 
for(int i=0; i<4; ++i) 
    ptr[i] = new MyClass(1, i); 

//use 

for(int i=0; i<4; ++i) 
    delete ptr[i]; 
delete[] ptr; 

這是稍微慢一點接入,而且更容易使用。

+1

哇,過度殺傷:-) –

+0

@KerrekSB:你有另外一種方法來構造一個具有不同參數的對象數組嗎?我想不出一個。 (不是說沒有,我只是想不出來) –

+0

那麼,OP的代碼實際上是正確的,基本上這樣做,所以我不知道現在的問題在哪裏... –