Singleton - tablica instance

0

Witam.
Mam problem z singletonem. kod wygląda tak:

class single
{
private:
	static single *instance[4];

	single(){}
public:
	static single* getInstance(int selector);

	inline void metody();
};

single* single::getInstance(int selector)
{
	if(instance[selector]==NULL)
	{
		instance[selector] = new single();

	}
	return instance[selector];
} /*<<-- ERROR undefined reference to `single::instance'*/

int main()
{
	single *OB1;
	OB1 = single::getInstance(0);
	OB1->metody();
}
 

Idea działania jest taka, że przy tworzeniu obiektu OB1 za pomocą getInstance(0), ma mi się zapisać w pierwszej komórce instance adres do nowo utworzonej klasy. Powtórne wywołanie funkcji z tym samym parametrem ma zwracać utworzony adres, a zmiana parametru utworzyć nową i zapisać w kolejnej komórce.
Kod nie kompiluje się o dostaję błąd " undefined reference to `single::instance' "

Czekam na pomoc i pozdrawiam :)

0

brakuje: single *single::instance[4]; gdzieś po deklaracji klasy.

0

No ale to ma być singleton czy mają być 4 instancje? :-/

0

Singleton to bardziej:

#include <cstdio>

class CClass
{
private:
	static CClass * s_pSingleton;
	int m_iSamplePrivateValue;
public:
	CClass();
	~CClass();

	static CClass * GetSingleton();

	void ShowValue();

	void SetValue(int iValue);
};

CClass * CClass::s_pSingleton = 0;

CClass::CClass()
{
	s_pSingleton = this;
}

CClass::~CClass()
{
}

CClass * CClass::GetSingleton()
{
	return s_pSingleton;
}

void CClass::ShowValue()
{
	printf("SamplePrivateValue = %i\n", m_iSamplePrivateValue);
}

void CClass::SetValue(int iValue)
{
	m_iSamplePrivateValue = iValue;
}


void func()
{
	CClass::GetSingleton()->ShowValue();
}

int main(int, char**)
{
	CClass * pClass = new CClass(); // this was copied to singleton
	pClass->SetValue(1234);
	func();
    delete pClass;
	return 0;
}

To co ty zrobiłeś to ja nie wiem co to jest :D

0

Dzięki "_13th_Dragon" twoja podpowiedź rozwiązała problem :)

1

Zrób coś w tym guście:

#include <iostream>
using namespace std;

struct single
  {
   struct group
     {
      struct data
        {
         int x,y,z;
        } instance[4];
     };
   group *operator->()const
     {
      static group g;
      return &g;
     }
  };
 
int main()
  {
   single()->instance[0].x=3;
   cout<<single()->instance[0].x<<endl;
   return 0;
  }

1 użytkowników online, w tym zalogowanych: 0, gości: 1