I am getting some errors when I try to put declaration and definition of a class into separatte hpp and cpp file. could you help me fix it please.
I am trying to manipulate a singleton like this:
sing.hpp:
class GlobalClass {
int m_value;
static GlobalClass *s_instance;
GlobalClass(int);
public:
int get_value();
void set_value(int v);
static GlobalClass *instance(); };
sing.cpp:
#include"sing.hpp"
GlobalClass::GlobalClass(int v = 0)
{
this->m_value = v;
}
int GlobalClass::get_value()
{
return this->m_value;
}
void GlobalClass::set_value(int v)
{
this->m_value = v;
}
static GlobalClass GlobalClass::*instance()
{
if (!s_instance)
s_instance = new GlobalClass;
return s_instance;
}
main.cpp:
#include "sing.hpp"
int main()
{
GlobalClass *s=0;
}
command and errors are:
~/workspace/singleton$ g++ main.cpp sing.cpp
sing.cpp: In function ‘GlobalClass GlobalClass::* instance()’:
sing.cpp:19:10: error: ‘s_instance’ was not declared in this scope
sing.cpp:2:1: error: ‘GlobalClass::GlobalClass(int)’ is private
sing.cpp:20:23: error: within this context
sing.cpp:21:12: error: ‘s_instance’ was not declared in this scope
Your definition of
instancehas two errors:staticqualifier is erroneous.The syntax for the return type got scrambled. The pointer belongs to the type, not the name of the function:
Furthermore, you also need to define the static member
s_instanceas others have noted.But this code has another problem: it leaks memory. Don’t use raw pointers.
Finally, this code isn’t thread safe and this may in some situtaions be a huge problem. Assuming that you can guarantee that your code is never going to run in multi-threaded scenarios, go ahead. Otherwise, you probably want to change it (and who can offer such a strong guarantee anyway?).