static members
Dec 10, 2013 at 4:28pm UTC
hi everyone
in .h
1 2 3 4 5 6 7 8 9 10 11
class chickens
{
private :
static Window * mWin;
static Renderer * mRen;
public :
....
....
Window * GetWindow();
Renderer * GetRenderer();
};
and called it in .cpp
1 2 3 4 5 6 7 8 9
Window * chickens::GetWindow()
{
return Window * chickens::mWin;
}
Renderer * chickens::GetRenderer()
{
return Renderer * chickens::mRen;
}
and the compiler gives this error
C:\Users\Ceset\Projects\Chickens\Classes\chickens.cpp:31: error: expected primary-expression before '*' token
return Window * chickens::mWin;
^
C:\Users\Ceset\Projects\Chickens\Classes\chickens.cpp:36: error: expected primary-expression before '*' token
return Renderer * chickens::mRen;
^
sorry i didnot get exactly static members in classes even though i read many times and google research also could not help. Can you tell me why it gives this error and how should i use statics in a class
Dec 10, 2013 at 4:34pm UTC
1 2 3 4 5
Window * chickens::GetWindow()
{
// return Window * chickens::mWin; <- no
return mWin; // <- yes
}
You only put the type before the variable when you are declaring/defining the variable.
You also don't need the chickens:: scope resolution here because you're already in the chickens class. (though adding it doesn't hurt, I suppose).
Dec 10, 2013 at 4:48pm UTC
i did it this way
1 2 3 4 5 6 7 8 9
Window * chickens::GetWindow()
{
return mWin;
}
Renderer * chickens::GetRenderer()
{
return mRen;
}
and it gives this error now
C:\Users\Ceset\Projects\Chickens\Classes\chickens.cpp:11: error: undefined reference to `chickens::mWin'
.....
.....
EDIT: i know what i did was nonsense. but in google people says i need to redefine(or such i couldnt get much) the variable to make linker happy(???).
Last edited on Dec 10, 2013 at 4:52pm UTC
Dec 10, 2013 at 5:12pm UTC
Declaration of static member vars isn't enough, you also need to "define" them so the linker knows where to put them.
In your cpp file, add these:
1 2
Window * chickens::mWin;
Renderer * chickens::mRen;
Dec 10, 2013 at 5:32pm UTC
thx that solved th problem
Dec 10, 2013 at 5:53pm UTC
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
// Add these lines and it should compile.
Window * chickens::mWin = nullptr ; // or whatenever initial address you want.
Renderer * chickens::mRen = nullptr ; // idem
//It would be better to scope it with the class name
Window * chickens::GetWindow()
{
return chickens::mWin;
}
Renderer * chickens::GetRenderer()
{
return chickens::mRen;
}
Last edited on Dec 10, 2013 at 5:57pm UTC
Topic archived. No new replies allowed.