singleton
#include "params.h" Params::instance().name = ui->lineEdit->text ().toStdString(); Params::instance().setNumber (ui->spinBox->value()); Params & p = Params::instance(); p.getNumber ();
Soubor params.h
#ifndef PARAMS_H #define PARAMS_H #include <string> using namespace std; class Params { public: string name; private: int number; public: int getNumber () { return number; } void setNumber (int n) { number = n; } public: Params(); private: static int cnt; static Params * obj; public: static Params & instance (); }; #endif // PARAMS_H
Soubor params.cpp
#include "params.h" #include <stdexcept> int Params::cnt = 0; Params * Params::obj = NULL; Params::Params() { cnt ++; if (cnt > 1) throw new runtime_error ("Too many instances"); } Params & Params::instance () { if (obj == NULL) obj = new Params (); return *obj; }
singleton.txt · Last modified: 2014/11/27 11:45 by 127.0.0.1