-1

I got my main class Game:

Game.h:

class Game{
public:
    Galaxian galaxians[6][10];
};

Game.cpp:

Nothing interesting, just filling the variables of the class array

Galaxian.h:

class Galaxian{
public:
   void update();
};

Galaxian.cpp:

Here is my problem: I want to access the galaxians array from the Game class, but I have no idea how! When I try game::galaxians I get the error "A nonstatic member reference must be relative to a specific object"

What I am trying to accomplish is that I can loop trough that array and change a value of each key in it.

How can I do that?

4

3 回答 3

2

This is because the galaxians member is an instance member, not a class (i.e. not a static) member. You should either (1) make an instance of Game available at the point where you need to access galaxians, or (2) make galaxians a static member.

If you decide on the first way, consider making Game a singleton; if you decide on the second way, do not forget to define your galaxians array in a cpp file, in addition to declaring it static in the header file.

于 2012-09-23T12:27:18.520 回答
1

Non-static members are bound to an instance of a class, not to the class itself. This is general OO, not specific to C++. So you either bind the access to an object, or the member to the class:

Game g;       //create an object of the class
g.galaxians;  //access the member through the object

or

class Game{
public:
    static Galaxian galaxians[6][10];  //bind the member to the class
};

//...

Game::galaxians;  //access it through the class

Which one you choose depends on your logic.

于 2012-09-23T12:27:05.263 回答
1

You need to access an instance of Game:

Game g;
g.galaxians[3][4] = ....;
于 2012-09-23T12:27:38.813 回答