首先我想澄清一下,您的代码中在
printCarNumbers
函数中存在一个错误,您试图使用
std::cout
将空值发送到标准输出,如下所示:
void printCarNumbers(Car *cars, int length)
{
for(int i = 0; i < length; i++)
std::cout << cars[i].printNo();
}
既然printNo()
函数是用来打印的,那么直接调用即可:
for(int i = 0; i < length; i++)
cars[i].printNo();
让我们回到主题,你正在尝试使用new
来分配一个对象数组,就像这样:
Car *mycars = new Car[userInput];
使用这种语法,实际上您正在尝试分配一个对象数组,其大小为userInput
(这就是我们想要的),但问题在于它尝试调用每个对象的默认构造函数,并且默认构造函数被声明为私有,因此它找不到它,这就是为什么您会得到那个错误:
cartest.cpp:5: error: ‘Car::Car()’ is private
相反,你需要以这种方式执行:
Car *mycars = (Car*) ::operator new (sizeof(Car));
// allocates memory by calling: operator new (sizeof(Car))
// but does not call Car's constructor
如评论中所述,以这种方式调用new
会为您分配内存,而不调用默认构造函数。有关更多详细信息,请查看new operator
现在,如果您想调用参数化构造函数,则需要为每个对象单独调用它,如下所示:
for(int i =0; i < userInput; i++)
new (&mycars[i]) Car(i + 1); // does not allocate memory -- calls: operator new (sizeof(Car), &mycars[i])
// but constructs an object at mycars[i]
你可能会感到困惑,因为我们再次调用了 new
,但是这种新的语法并没有分配任何内存,它只是调用了索引对象的构造函数。
以下是完整的可运行代码,供任何人测试:
#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++)
cars[i].printNo();
}
int main()
{
int userInput = 10;
Car *mycars = (Car*) ::operator new (sizeof(Car));
for(int i =0;i < userInput;i++)
new (&mycars[i]) Car(i+1);
printCarNumbers(mycars,userInput);
return 0;
}
我知道我来晚了,但也许有人会觉得这很有用。如果有任何错误的陈述,请随时纠正我。
operator new []
总是调用默认构造函数。但是C++11有一个解决方案,如下所示:链接。 - rustyx