我正在建立一个名为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给了我编译器错误“ error:没有匹配的函数来调用'Ball :: Ball()'”。
我有4个具有不同签名的Ball构造函数,没有一个看起来像:“ Ball()”。

我尝试添加一个构造函数“ Ball :: Ball()”,然后对其进行编译,但是我觉得我应该能够为一个对象分配空间,然后实例化它们。

我想知道的是:为什么在上面的代码中没有构造函数“ Ball :: Ball()”,为什么不能为对象Ball分配空间?
并且:如果可以通过某种方式在没有构造函数“ Ball :: Ball()”的情况下分配空间,我该怎么做呢?

我知道我可以创建构造函数“ Ball :: Ball()”并为对象提供一些虚拟值,然后将它们设置为所需的值,但是这样做令我感到不舒服,因为我不知道为什么我不能只是“分配空间->实例化对象”。我希望我能解释我的问题。谢谢!

最佳答案

可以使用提供的大小来调用new T,而不是获取内存并调用ctor的operator new。唯一为您提供记忆,别无其他。然后,您可以在正确计算的位置上调用placement new,它将仅调用您的ctor。在您发布的位置,而不是重新分配。在google中搜索提供的条款以查看示例。

但是通常您不应该执行任何操作,使用std::vector<Ball>可以轻松完成任务并提高安全性。

关于c++ - 在C++中分配对象的二维数组时出错,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17251030/

10-12 06:20