Confused with object arrays in C++

前端 未结 7 677
后悔当初
后悔当初 2021-01-30 03:56

So I first learned Java and now I\'m trying to switch over to C++. I\'m having a little difficulty getting arrays to work correctly.

Right now I am simply trying to crea

7条回答
  •  春和景丽
    2021-01-30 03:59

    Your types don't match. And it's no wonder, you're trying to store a Player* into an already-allocated Player!

    Player* players = new Player[1];
    

    This creates an array of length 1, containing an instantiated Player, and stores the whole thing into a Player*. The type of players[0] is going to be Player.

    players[0] = new Player(...)
    

    This attempts to create a new Player* and store it in the array. But the array contains Player objects. You should just say

    players[0] = Player(...)
    

    Alternatively, and I'm going to guess this is more appropriate for you, you should stop using new entirely, and use a std::vector.

    std::vector players;
    players.push_back(Player(playerWidth, playerHeight, 20, 1));
    // or players.emplace_back(playerWidth, playerHeight, 20, 1);
    

    Not only is this much easier to use, but you also don't have to remember to delete it later. When the std::vector goes out of scope, it will automatically destruct. Also, unlike your array, std::vector can contain any number of objects, so you can add new players or delete existing players at will.

    There are other data structures as well that may possibly be more suited for you, depending on your exact use, but std::vector is a good starting point.

提交回复
热议问题