PDA

View Full Version : [C++] pattern singleton


ndakota
07-04-2009, 15:17
ciao a tutti con l'aiuto del libro desing patterns stavo provando a guardare qualcosa.. volevo iniziare dal pattern singleton che mi sembra piuttosto semplice ma ho già avuto le prime difficoltà.. i codici sono questi:

Singleton.h


#ifndef SINGLETON_H
#define SINGLETON_H

class Singleton
{
public:
static Singleton* Instance();
protected:
Singleton();
private:
static Singleton* _instance;
};

#endif


Singleton.cpp


#include <iostream>
#include "Singleton.h"

Singleton* Singleton::_instance = 0;

Singleton* Singleton::Instance()
{
if(_instance == 0)
_instance = new Singleton;

else
std::cout << "another instance of singleton can't be instanced" << std::endl;

return _instance;
}


main.cpp


#include <iostream>
#include "Singleton.h"

int main()
{
Singleton* a = Singleton.Instance();
Singleton* b = Singleton.Instance();
Singleton* c = Singleton.Instance();

return 0;
}


nel main a parte i tre warning di variabili non utilizzate ricevo anche tre errori del tipo "expected primary-expression before '.' token"..

dove sbaglio?

BrutPitt
07-04-2009, 15:50
La dichiarazione e':

static Singleton* Instance();

quindi:

Singleton* a = Singleton::Instance();

javaboy
07-04-2009, 16:24
A parte il tuo errore.
Ricordati di non dare alle variabili nomi che iniziano per underscore.

shinya
07-04-2009, 16:37
A parte il tuo errore.
Ricordati di non dare alle variabili nomi che iniziano per underscore.
E perchè?

javaboy
07-04-2009, 17:05
E perchè?

11. Style: Try to avoid names with leading underscores. Yes, I've habitually used them, and yes, popular books like "Design Patterns" (Gamma et al) do use it... but the standard reserves some leading-underscore identifiers for the implementation and the rules are hard enough to remember (for you and for compiler writers!) that you might as well avoid this in new code.

Da Exceptional C++ di Sutter.

shinya
07-04-2009, 17:09
11. Style: Try to avoid names with leading underscores. Yes, I've habitually used them, and yes, popular books like "Design Patterns" (Gamma et al) do use it... but the standard reserves some leading-underscore identifiers for the implementation and the rules are hard enough to remember (for you and for compiler writers!) that you might as well avoid this in new code.

Da Exceptional C++ di Sutter.
Ah, Style!
...
http://en.wikipedia.org/wiki/Fashion_victim

ndakota
07-04-2009, 17:13
grazie ora funziona, non avevo mai chiamato un metodo statico in C++.. sbaglio o negli altri linguaggi si fa come avevo scritto io?? :p

javaboy
07-04-2009, 17:22
Ah, Style!
...
http://en.wikipedia.org/wiki/Fashion_victim

:sofico: