13.01.2015 Views

Pensar en C++ (Volumen 1) - Grupo ARCO

Pensar en C++ (Volumen 1) - Grupo ARCO

Pensar en C++ (Volumen 1) - Grupo ARCO

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

✐<br />

✐<br />

✐<br />

“Volum<strong>en</strong>1” — 2012/1/12 — 13:52 — page 293 — #331<br />

✐<br />

10.3. Miembros estáticos <strong>en</strong> <strong>C++</strong><br />

//: C10:StaticMemberFunctions.cpp<br />

class X {<br />

int i;<br />

static int j;<br />

public:<br />

X(int ii = 0) : i(ii) {<br />

// Non-static member function can access<br />

// static member function or data:<br />

j = i;<br />

}<br />

int val() const { return i; }<br />

static int incr() {<br />

//! i++; // Error: static member function<br />

// cannot access non-static member data<br />

return ++j;<br />

}<br />

static int f() {<br />

//! val(); // Error: static member function<br />

// cannot access non-static member function<br />

return incr(); // OK -- calls static<br />

}<br />

};<br />

int X::j = 0;<br />

int main() {<br />

X x;<br />

X* xp = &x;<br />

x.f();<br />

xp->f();<br />

X::f(); // Only works with static members<br />

} ///:~<br />

Puesto que no ti<strong>en</strong><strong>en</strong> el puntero this, los métodos estáticos no pued<strong>en</strong> acceder<br />

a atributos no estáticos ni llamar a métodos no estáticos.<br />

Note el lector que <strong>en</strong> main() un miembro estático puede seleccionarse utilizando<br />

la habitual sintaxis de punto o flecha, asociando la función con el objeto, pero<br />

también sin objeto (ya que un miembro estático está asociado con una clase, no con<br />

un objeto particular), utilizando el nombre de la clase y el operador de resolución de<br />

ámbito.<br />

He aquí una interesante característica: Debido a la forma <strong>en</strong> la que se inicializan<br />

los objetos miembro estáticos, es posible poner un atributos estático de la misma<br />

clase d<strong>en</strong>to de dicha clase. He aquí un ejemplo que tan solo permite la exist<strong>en</strong>cia de<br />

un único objeto de tipo Egg defini<strong>en</strong>do el constructor privado. Puede acceder a este<br />

objeto pero no puede crear ningún otro objeto tipo Egg:<br />

//: C10:Singleton.cpp<br />

// Static member of same type, <strong>en</strong>sures that<br />

// only one object of this type exists.<br />

// Also referred to as the "singleton" pattern.<br />

#include <br />

using namespace std;<br />

class Egg {<br />

293<br />

✐<br />

✐<br />

✐<br />

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!