Having problems with accessing struct

2020-05-01 04:43发布

问题:

I think i may be losing it but can anyone double check my sanity? This is the only code i wrote in a new file to see my project file is not messed up.

Error: This declaration has no storage class or type specifier

Error: Expected a ";"

回答1:

On a global level you can only have declarations and definitions, not statements (like g.a = 1; is) or expressions.



回答2:

Also why not use by static initialization?

Game g = { 1 };


回答3:

Have some function to have the executable statement, for example,

Game Init() {
    Game result;
    result.a = 1; // g is global
    return result;
}

Game g = Init();

Even better to have a class called Game and have the constructor to do the initialization.

class Game {
  int a;
  public:  
  Game(int a_):a(a_){}
};

Game g(1);