struct UIQstate{ unsigned int left,right,up,down,jump,shoot; UIQstate(): left(0), right(0), up(0), down(0), jump(0), shoot(0) {} unsigned int size() const {return 6;}};
C++ default initialization
Is there any way to get numerical types default initialized to 0 in C++ without explicitly initializing them? It seems like there should be a better way to code this.
Would this:
UIQstate(): left(), right(), up(), down(), jump(), shoot() {}
Have the desired effect? (IIRC, this will zero-initialize variables of primitive types. However, I may not be remembering correctly.)
Even if jyk's code works (I think it should), I wouldn't use it: The code is less obvious than the OP's.
struct UIQstate{ enum ACTIONS{left,right,up,down,jump,shoot,enum_end}; unsigned int actions[enum_end]; UIQstate(): actions() {} unsigned int size() const {return static_cast<unsigned>(enum_end);}};
One downside of that is that it complicates any code which uses the struct. For example,
Is a little less readable than
++myState.at(UIQstate::DOWN);
Is a little less readable than
++myState.down;
A slightly different variation:
Sure it's not as readable as it could be, but it certainly reduces the amount of work it takes when you want to provide UIQstate::operator+(const UIQstate&), UIQstate::operator*, and etc. This is especially useful for a RPG stats structure, for example.
However, if it's readability you're going for, then what you currently have is the best way to go.
class UIQstate {public: enum Actions { left, right, up, down, jump, shoot, num_actions };public: UIQstate() : actions() { // C4351 }public: unsigned& operator[] ( Actions idx ) { return actions[ static_cast<int>( idx ) ]; } const unsigned& operator[] ( Actions idx ) const { return actions[ static_cast<int>( idx ) ]; } unsigned numActions() const { return num_actions; }private: unsigned actions[num_actions];};int main () { UIQstate t; t[UIQstate::up] ++; cout << t[UIQstate::up] << endl;}
Sure it's not as readable as it could be, but it certainly reduces the amount of work it takes when you want to provide UIQstate::operator+(const UIQstate&), UIQstate::operator*, and etc. This is especially useful for a RPG stats structure, for example.
However, if it's readability you're going for, then what you currently have is the best way to go.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement