Statyczna metoda klasy, zapis z którym się jeszcze nie spotkałem

0

Chciałbym, abyście pomogli mi z analizą kodu, który znalazłem.

#include <iostream>
#include <string>
using namespace std;

class ScreenManager
{
private:
    ScreenManager();

    string text;

public:
    ~ScreenManager();
    static ScreenManager &GetInstance();
    void SetText( string text );
    void DrawText( );
};

int main()
{
    ScreenManager::GetInstance().SetText("Test");
    ScreenManager::GetInstance().DrawText();
}

ScreenManager &ScreenManager::GetInstance()
{
    static ScreenManager instance;
    return instance;
}

ScreenManager::ScreenManager(void)
{
}

ScreenManager::~ScreenManager(void)
{
}

void ScreenManager::SetText( string text )
{
    this -> text = text;
}

void ScreenManager::DrawText( )
{
    cout << text << endl;
}


 

Nie rozumiem operacji wykonanej w tym momencie:
static ScreenManager &GetInstance();

Tworzy się tu statyczna funkcja typu klasy, odbierana przez referencje ?
Potem co się dzieje w środku, po co tworzy się ten obiekt statyczny, i co on niby zwraca.
A na końcu: ScreenManager::GetInstance().SetText("Test");
Rozumiem że tak możemy odwoływać się tą statyczną funkcją, do reszty metod z klasy, jednak jak to wszystko działa ?

0

Znacznie lepszym rozwiązaniem jest to:

#include <iostream>
#include <string>
using namespace std;
 
class ScreenManager
  {
   private:
   typedef struct Instance
      {
       string text;
       void setText(const string &text) { this->text=text; }
       string getText() const { return text; }
      };
   public:
   Instance *operator->() const
     {
      static Instance inst;
      return &inst;
     }
  };
 
int main()
  {
   ScreenManager()->setText("Test");
   cout<<ScreenManager()->getText()<<endl;
   return 0;
  }

O wiele mniej kodu i bardziej elegancko.

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