#include <iostream>
using namespace std;
class EquipmentPiece
{
public:
EquipmentPiece(int IDNumber)
{
this->IDNumber = IDNumber;
}
void PrintOut()
{
cout << IDNumber << endl;
}
private:
int IDNumber;
};
int main()
{
// 为大小为 10 的数组 分配足够的内存
// EquipmentPiece 对象;
// operator new[] 函数
char *rawMemory = new char[10*sizeof(EquipmentPiece)];
// 或者void *rawMemory = operator new[](10*sizeof(EquipmentPiece));
// EquipmentPiece *bestPieces = static_cast<EquipmentPiece*>(rawMemory);
// make bestPieces point to it so it can be treated as an
// EquipmentPiece array
EquipmentPiece *bestPieces = reinterpret_cast<EquipmentPiece*>rawMemory;
// construct the EquipmentPiece objects in the memory
// 使用"placement new"
for (int i = 0; i < 10; ++i)
new (&bestPieces[i]) EquipmentPiece(i);
for (int i = 0; i < 10; ++i)
bestPieces[i].PrintOut();
// 以与构造 bestPieces 对象相反的顺序
// 解构它。
for (int i = 9; i >= 0; --i)
bestPieces[i].~EquipmentPiece();
// deallocate the raw memory
delete[]rawMemory;
return 0;
}
运行结果如图: