开发者

Need ideas on how to store something in C++

I am working in a large project for a g开发者_如何学JAVAame which involves Javascript, Jquery, C++, and Awesomium. Right now I will only focus on C++ for this question. In the game, there are supposed to be two different "jobs" (you can either be a scientist or a ditchman). I need to make a way to check to see which job you currently are (you can change in-game). I'm trying to make a temporary way, since I'm pretty novice to C++ and I'm sure the task will eventually be handed to someone.

I'm uncertain as to how to keep this "variable" stored. Global variables in C++ are apparently a big no-no. I should use static... methods? I just don't know. The actual program itself is too large to include any example without a lot of editing and effort. If you have any suggestions or questions, I'd be happy to hear and try to answer.

EDIT I need this implementation of jobs and switching before I can test new functionality of a JS map. That's really the reason for doing this, so when I was making the title that was on my mind.


You use an "object". These are collections of state and variables that you bring around with you, effectively.

enum Job {
    Scientist,
    Ditchman
};

class Player {
    Job j;
public:
    void job(Job newjob) { j = newjob; }
    Job job() { return j; }
    Player() { job = Scientist; }
};

int main() {
    Player p;
    p.job(Ditchman);
    //....
    p.job(Scientist);
}

In this case, the Player::j variable is accessible to all Player functions, and by creating an instance of Player, we create an instance of j also. If other functions need access to our Player, we would typically pass by reference in this case, as we don't want to create more Players.


I would recommend using an oo approach that uses a base class called job and derived classes called scientist and ditchman. Each derived object from job would be kept in some kind of array or container and use polymorphic calls to perform the correct specialized functions, which should have a pure virtual base class definition and then over-ridden in each derived class.

You said that "you can change in-game" from a scientist to a ditchman. So, if you use this approach, then you would need a conversion function that does all the work necessary to convert between a scientist object and a ditchman object.

You should never use global variables. Also be aware of circular references (one class calling a method in another class and then that class calling back into the first class) and try not to to that either. It is ok to have some sort of container like a vector, map, or hash table hold a list of the objects in the game and pass a pointer (or reference) to that object to other classes that need it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜