C++ 與“類”有關的注意事項總結(十):類對象數組初始化(三種方法)

來源:互聯網
上載者:User

類對象數組初始化

 

如有一個如下類:

class EquipmentPiece {
private:
int IDNumber;
public:
EquipmentPiece(int IDNumber) : IDNumber(IDNumber) {};
};

 

以下列出幾種初始化的方法:

<一>、對象數組

int ID1, ID2, ID3;
EquipmentPiece bestPieces[] = { EquipmentPiece(ID1), EquipmentPiece(ID2), EquipmentPiece(ID3) };

注意:

EquipmentPiece bestPieces[10]; //no appropriate default constructor available
EquipmentPiece *bestPieces = new EquipmentPiece[10]; //no appropriate default constructor available

當然,如果你將建構函式參數全都設了預設值,以上兩種寫法也成功,如將類中建構函式修改如下:
...
EquipmentPiece(int IDNumber = 0) : IDNumber(IDNumber) {};
...

 

<二>、指標數組

typedef EquipmentPiece* PEP; //PEP是個指向EquipmentPiece的指標

PEP bestPieces[10]; //等同於 PEP *bestPieces = new PEP[10];

//然後初始化
for(int i = 0; i < 10; i++){
bestPieces[i] = new EquipmentPiece( IDNumber );
}

注意:
要記得將此數組所指的所有對象刪除。如果忘了會產生資源流失。還有就是該方法與對象數組相比需要額外記憶體用於存放指標。(過度使用記憶體 這一問題可以避免,見第三種方法)

 

<三>、使用placement new(定位new操作符)

方法是:先為此數組分配raw memory,然後使用"placement new"在這塊記憶體上構造EquipmentPiece objects;

 

//分配足夠的raw memory,給一個預備容納10個EquipmentPiece objects的數組使用
void *rawMemory = operator new(10*sizeof(EquipmentPiece));

//讓bestPieces指向此記憶體,使這塊記憶體被視為一個EquipmentPiece數組
EquipmentPiece *bestPieces = reinterpret_cast<EquipmentPiece*>(rawMemory);

//利用"placement new"構造這塊記憶體中的EquipmentPiece objects。
int IDNumber = 0;
for(int i = 0; i < 10; i++){
new (&bestPieces[i]) EquipmentPiece( IDNumber );
}

 

注意:該方法維護比較困難。在數組內對象結束生命時,要以手動方式調用destructors,最後還得調用operator delete釋放raw memory。

//將bestPieces中對象以構造次序的反序析構掉
for(i = 0; i < 10; i++){
bestPieces[i].~EquipmentPiece();
}

//釋放raw memory
operator delete (rawMemory);

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.