オブジェクト Ball の 2 次元配列を格納する ParticleMatrix というクラスを作成しています。それらに動的にスペースを割り当てたい。コードは次のようになります。
/*
* 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 を実行すると、" error: no matching function for call to 'Ball::Ball()' " というコンパイラ エラーが表示されます。Ball には、異なる署名を持つ 4 つのコンストラクターがありますが、「Ball()」のようなものはありません。
コンストラクター「Ball::Ball()」を追加してみましたが、コンパイルされますが、オブジェクトにスペースを割り当てて後でインスタンス化できるはずだと感じています。
私が疑問に思っているのは、上記のコードにコンストラクター「Ball::Ball()」がないと、オブジェクト Ball にスペースを割り当てられないのはなぜですか? そして:コンストラクター「Ball::Ball()」なしで何らかの方法でスペースを割り当てることができる場合、どうすればそれを行うことができますか?
コンストラクター "Ball::Ball()" を作成し、オブジェクトにダミーの値を与えて、後で必要な値に設定できることはわかっていますが、単に "スペースの割り当て -> オブジェクトのインスタンス化". 私の問題を説明できたことを願っています。ありがとう!