Ejemplo de Herencia
Posted on July 16th, 2005 in C++, Código |
Ejemplo de Herencia en C++. POO.
C++:
-
#include <iostream.h>
-
#include <stdlib.h>
-
-
class Padre
-
{
-
protected:
-
char* _nombre;
-
int _edad;
-
-
public:
-
Padre():_edad(-1)
-
{
-
_nombre = new char[20];
-
strcpy(_nombre, "Default");
-
}
-
Padre(char* n, int a = 1):_edad(a)
-
{
-
_nombre = new char[20];
-
strcpy(_nombre, n);
-
}
-
-
inline int edad()const { return _edad; }
-
char* nombre() const
-
{
-
char* temp = new char[20];
-
strcpy(temp, _nombre);
-
return temp;
-
}
-
-
friend ostream& operator <<(ostream& out, const Padre& rhs)
-
{
-
out <<"nombre: " <<rhs.nombre() <<" edad: " <<rhs.edad();
-
return out;
-
}
-
};
-
-
class Hijo : public Padre
-
{
-
protected:
-
int _matricula;
-
char* _escuela;
-
public:
-
-
Hijo(char* nombrePadre, int edadPadre, char* nEscuela, int nMatricula): Padre(nombrePadre, edadPadre)
-
{
-
_matricula = nMatricula;
-
_escuela = new char[20];
-
strcpy(_escuela, nEscuela);
-
}
-
-
inline int matricula(){ return _matricula; }
-
-
char* escuela()
-
{
-
char* temp = new char[20];
-
strcpy(temp, _escuela);
-
return temp;
-
}
-
-
friend ostream& operator <<(ostream& out, const Hijo &rhs)
-
{
-
out <<static_cast<Padre> (rhs) <<" escuela: " <<rhs._escuela <<" matricula : " <<rhs._matricula;
-
return out;
-
}
-
};
-
-
int main(int args, char** argv)
-
{
-
bool cond = false;
-
if(args == 2)
-
cond = !strcmp(argv[1], "-debug");
-
-
if(cond) cout <<"Creando objeto Padre " <<endl;
-
Padre p1("Alejandro", 24);
-
-
if(cond) cout <<"Creando objeto Hijo " <<endl;
-
Hijo h1("Junior", 15, "Tec", 922382);
-
-
cout <<p1 <<endl;
-
cout <<h1 <<endl;
-
system("PAUSE");
-
return 0;
-
}
Popularidad: 11%

