Carlos Romero Carlos Romero - 11 days ago 6
C++ Question

c++: Proper way to initialize static fields of member struct

I got this:

// mouse.h
class Mouse {
private:
struct Pos {
static GLfloat x;
static GLfloat y;
};
static Pos last;
}


and this:

// mouse.cpp
// 1)
Mouse::Pos Mouse::last = {};
// 2)
Mouse::Pos Mouse::last = { 0.0, 0.0 };
// 3)
Mouse::last.x = 0.0f;
Mouse::last.y = 0.0f;


1)
,
2)
and
3)
are the attempts I've made at initializing that thing. I understand that the header should declare that
last
is
static
, and that the source should initialize it, but something has been wrong with all my attempts. Could someone please tell me the correct way to do such a thing? Am I missing some very important point? Is this nonsense? It is important that the fields are static. Thanks.

Answer

You don't need to declare Pos content as static.

// mouse.h

class Mouse {
  private:
    struct Pos {
      GLfloat x;
      GLfloat y;
    };    
    static Pos last;
}

Mouse::Pos Mouse::last = { 0.0, 0.0 };

This should work too

Comments