Pensar en C++ (Volumen 1) - Grupo ARCO
Pensar en C++ (Volumen 1) - Grupo ARCO
Pensar en C++ (Volumen 1) - Grupo ARCO
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 258 — #296<br />
✐<br />
Capítulo 9. Funciones inline<br />
r.height(2 * r.width());<br />
r.width(2 * r.height());<br />
} ///:~<br />
El constructor usa la lista de inicialización (brevem<strong>en</strong>te introducida <strong>en</strong> el capítulo<br />
8 y ampliam<strong>en</strong>te cubierta <strong>en</strong> el capitulo 14) para asignar valores a wide y high<br />
(usando el formato de pseudo-constructor para los tipos de datos básicos).<br />
No puede definir métodos que t<strong>en</strong>gan el mismo nombre que los atributos, de modo<br />
que puede que se si<strong>en</strong>ta t<strong>en</strong>tado de distinguirlos con un guión bajo al final. Sin<br />
embargo, los id<strong>en</strong>tificadores con guiones bajos finales están reservados y el programador<br />
no debería usarlos.<br />
En su lugar, debería usar «set» y «get» para indicar que los métodos son accesores<br />
y mutadores.<br />
//: C09:Rectangle2.cpp<br />
// Accessors & mutators with "get" and "set"<br />
class Rectangle {<br />
int width, height;<br />
public:<br />
Rectangle(int w = 0, int h = 0)<br />
: width(w), height(h) {}<br />
int getWidth() const { return width; }<br />
void setWidth(int w) { width = w; }<br />
int getHeight() const { return height; }<br />
void setHeight(int h) { height = h; }<br />
};<br />
int main() {<br />
Rectangle r(19, 47);<br />
// Change width & height:<br />
r.setHeight(2 * r.getWidth());<br />
r.setWidth(2 * r.getHeight());<br />
} ///:~<br />
Por supuesto, los accesores y mutadores no ti<strong>en</strong><strong>en</strong> porqué ser simples tuberías<br />
hacia las variables internas. A veces, pued<strong>en</strong> efectuar cálculos más sofisticados. El<br />
sigui<strong>en</strong>te ejemplo usa las funciones de tiempo de la librería C estándar para crear<br />
una clase Time:<br />
//: C09:Cpptime.h<br />
// A simple time class<br />
#ifndef CPPTIME_H<br />
#define CPPTIME_H<br />
#include <br />
#include <br />
class Time {<br />
std::time_t t;<br />
std::tm local;<br />
char asciiRep[26];<br />
unsigned char lflag, aflag;<br />
void updateLocal() {<br />
258<br />
✐<br />
✐<br />
✐<br />
✐