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 419 — #457<br />

✐<br />

14.5. Funciones que no heredan automáticam<strong>en</strong>te<br />

objeto "vehículo" - un coche no conti<strong>en</strong>e un vehículo, es un vehículo. La relación<br />

"es-un" es expresado con la her<strong>en</strong>cia y la relación "ti<strong>en</strong>e un" es expresado con la<br />

composición.<br />

Subtipado<br />

Ahora suponga que desea crear un objeto del tipo ifstream que no solo abre un<br />

fichero sino que también guarde el nombre del fichero. Puede usar la composición e<br />

alojar un objeto ifstream y un string <strong>en</strong> la nueva clase:<br />

//: C14:FName1.cpp<br />

// An fstream with a file name<br />

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

#include <br />

#include <br />

#include <br />

using namespace std;<br />

class FName1 {<br />

ifstream file;<br />

string fileName;<br />

bool named;<br />

public:<br />

FName1() : named(false) {}<br />

FName1(const string& fname)<br />

: fileName(fname), file(fname.c_str()) {<br />

assure(file, fileName);<br />

named = true;<br />

}<br />

string name() const { return fileName; }<br />

void name(const string& newName) {<br />

if(named) return; // Don’t overwrite<br />

fileName = newName;<br />

named = true;<br />

}<br />

operator ifstream&() { return file; }<br />

};<br />

int main() {<br />

FName1 file("FName1.cpp");<br />

cout

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

Saved successfully!

Ooh no, something went wrong!