#include <iostream>
class Car
{
private:
Car(){};
int _no;
public:
Car(int no)
{
_no=no;
}
void printNo()
{
std::cout<<_no<<std::endl;
}
};
void printCarNumbers(Car *cars, int length)
{
for(int i = 0; i<length;i++)
std::cout<<cars[i].printNo();
}
int main()
{
int userInput = 10;
Car *mycars = new Car[userInput];
for(int i =0;i < userInput;i++)
mycars[i]=new Car[i+1];
printCarNumbers(mycars,userInput);
return 0;
}
我想创建一个汽车阵列,但出现以下错误:
cartest.cpp: In function ‘int main()’:
cartest.cpp:5: error: ‘Car::Car()’ is private
cartest.cpp:21: error: within this context
有没有办法在不公开 Car() 构造函数的情况下进行此初始化?
最佳答案
您可以像这样使用 placement-new:
class Car
{
int _no;
public:
Car(int no) : _no(no)
{
}
};
int main()
{
void *raw_memory = operator new[](NUM_CARS * sizeof(Car));
Car *ptr = static_cast<Car *>(raw_memory);
for (int i = 0; i < NUM_CARS; ++i) {
new(&ptr[i]) Car(i);
}
// destruct in inverse order
for (int i = NUM_CARS - 1; i >= 0; --i) {
ptr[i].~Car();
}
operator delete[](raw_memory);
return 0;
}
来自 More Effective C++ 的引用 - Scott Meyers:
第 4 条 - 避免不必要的默认构造函数
关于c++ - 没有默认构造函数的对象数组初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26570607/