I’m new to using vectors…I just started studying them today. I’m trying to create a vector for my enemy class so I can dynamically create them, but I can’t seem to figure out how to use the class functions…
Here is the class…
class Enemy
{
private:
SDL_Surface *enemy;
public:
Enemy();
~Enemy();
enum Direction { UP, DOWN, LEFT, RIGHT } direction;
SDL_Rect position;
bool alive;
int setAttributes(int x, int y, int w, int h);
void update();
bool checkCollision();
};
Then I want to create a vector for the enemies in the game…
vector<Enemy> enemy;
Then I try to call the class functions like this…
enemy->setAttributes(0, 50, 32, 32);
enemy->update();
But when I compile, I get the following errors…
~/code/cpp/sdl$ g++ -o name main.cpp game.cpp player.cpp bullet.cpp enemy.cpp level.cpp -lSDL -lSDL_image -lSDL_ttf -lSDL_mixer
level.cpp: In constructor ‘Level::Level()’:
level.cpp:14: error: base operand of ‘->’ has non-pointer type ‘std::vector<Enemy, std::allocator<Enemy> >’
level.cpp: In member function ‘void Level::update()’:
level.cpp:28: error: base operand of ‘->’ has non-pointer type ‘std::vector<Enemy, std::allocator<Enemy> >’
What am I doing wrong here?
A vector is not a pointer (and does not act like one), and hence does not have an
operator->defined. Using a vector ofEnemys is just like using an array of them with the subscript operator:The reason you can use
operator->on arrays is that arrays convert to pointers, and thusis equivalent to
which is in turn equivalent to
However, just because this is possible does not mean it is a good idea: people will have much less trouble understanding your code if you write
enemies[0].update()instead ofenemies->update().If you want to go through a
vector<Enemy>as you could with a pointer to an array, you should doIf you’re using C++11 and are lazy, you can write
autoinstead ofstd::vector<Enemy>::iteratorand the compiler will figure out the type for you. (You may also want to store the value ofenemies.end()outside the loop so that you don’t call the function each iteration, but this may be optimised out anyway).