我正在构建一个名为 ParticleMatrix 的类,它存储对象 Ball 的二维数组。我想为他们动态分配空间。代码看起来像这样。
/*
* allocateParticle takes a width w, height h, restlength RL then allocates space for
* and constructs a 2D array of Particles of subclass Ball.
*/
void ParticleMatrix::allocParticles(int w, int h, float RL)
{
// Gets the number of particles in the xDirection
xPart = getNrPart(w,RL);
// Gets the number of particles in the yDirection
yPart = getNrPart(h,RL);
// Allocates a row of pointers to pointers.
ballArray = new Ball*[xPart];
// The ID of the particles.
int ID = 0;
// For every particle in the xDirection
for(int x = 0; x<xPart; x++)
{
// Allocate a row of Ball-pointers yPart long.
ballArray[x] = new Ball[yPart];
// For every allocated space
for(int y = 0; y<yPart; y++)
{
// Construct a Ball
ballArray[x][y] = Ball( ID, RL*(float)x, RL*(float)y);
ID++;
}
}
}
问题出现在“ballArray[x] = new Ball[yPart]”这一行。CodeBlocks 给了我编译器错误“错误:没有匹配函数调用 'Ball::Ball()'”。我有 4 个具有不同签名的 Ball 构造函数,没有一个看起来像:“Ball()”。
我曾尝试添加一个构造函数“Ball::Ball()”,然后它会编译,但我觉得我应该能够为一个对象分配空间,然后再实例化它们。
我想知道的是:为什么我不能在上面的代码中没有构造函数“Ball::Ball()”的情况下为对象 Ball 分配空间?并且:如果可以在没有构造函数“Ball::Ball()”的情况下以某种方式分配空间,我将如何去做?
我知道我可以创建构造函数“Ball::Ball()”并为对象提供一些虚拟值,然后将它们设置为所需的值,但这样做我感到不舒服,因为我不知道为什么我不能只是“分配空间 -> 实例化对象”。我希望我能够解释我的问题。谢谢!