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

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

✐<br />

✐<br />

✐<br />

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

✐<br />

Capítulo 7. Sobrecarga de funciones y argum<strong>en</strong>tos por defecto<br />

int Stash::count() {<br />

return next; // Number of elem<strong>en</strong>ts in CStash<br />

}<br />

void Stash::inflate(int increase) {<br />

assert(increase >= 0);<br />

if(increase == 0) return;<br />

int newQuantity = quantity + increase;<br />

int newBytes = newQuantity * size;<br />

int oldBytes = quantity * size;<br />

unsigned char* b = new unsigned char[newBytes];<br />

for(int i = 0; i < oldBytes; i++)<br />

b[i] = storage[i]; // Copy old to new<br />

delete [](storage); // Release old storage<br />

storage = b; // Point to new memory<br />

quantity = newQuantity; // Adjust the size<br />

} ///:~<br />

Cuando utiliza el primer constructor no se asigna memoria alguna para storage.<br />

La asignación ocurre la primera vez que trata de añadir (con add()) un objeto y<br />

<strong>en</strong> cualquier mom<strong>en</strong>to <strong>en</strong> el que el bloque de memoria actual se exceda <strong>en</strong> add().<br />

Ambos constructores se prueban <strong>en</strong> este programa de ejemplo:<br />

//: C07:Stash3Test.cpp<br />

//{L} Stash3<br />

// Function overloading<br />

#include "Stash3.h"<br />

#include "../require.h"<br />

#include <br />

#include <br />

#include <br />

using namespace std;<br />

int main() {<br />

Stash intStash(sizeof(int));<br />

for(int i = 0; i < 100; i++)<br />

intStash.add(&i);<br />

for(int j = 0; j < intStash.count(); j++)<br />

cout

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

Saved successfully!

Ooh no, something went wrong!