C ++在类中设置数组值

时间:2011-09-15 05:40:19

标签: c++ arrays class

我遇到了一个看起来很简单的概念。我有一个这样的课:

class Projectile
{
public:
    int count;
    int projectiles[1][3];

    Projectile();
    void newProjectile();

};

Projectile::Projectile()
{
    count = 0;
}

void Projectile::newProjectile()
{
    projectiles[0][0] = { 1, 2, 3 };
}

我正在尝试在projectiles数组中设置值,我必须这样做不正确。如何动态地将一组值添加到此属性中?

3 个答案:

答案 0 :(得分:3)

projectiles[0][0]指的是二维数组中的特定位置,其类型为int

如果您想动态添加项目,则可以使用std::vector<int>(请参阅here

答案 1 :(得分:2)

 projectiles[0][0] = { 1, 2, 3 };

这不正确。初始化列表只能在声明时给出。您必须将分配值独立地分配给数组元素的每个位置。 std::vector<std::vector> twoDimArray;就是你想要的。

struct foo{

    std::vector<std::vector<int> > twoDimArray;
    void create(int size){

        std::vector<int> oneDimArray(size);
        // vector as of now can just accommodate size number of elements. They aren't
        // assigned any values yet.


        twoDimArray.push_back(oneDimArray); // Copy it to the twoDimArray

        // Now if you wish to increase the size of each row, just push_back element to 
        //  that row. 
        twoDimArray[0].push_back(8);
    }
};

答案 2 :(得分:1)

试试这个

void Projectile::newProjectile()
{
    projectiles[0][0] = 1;
    projectiles[0][1]=2;
    projectiles[0][2]=3;

}
相关问题