abr 19
Bien continuando con esta serie de Post dónde se verán todas las perradas que aparecen en C++ gracias al mal diseño y a la mala programación. os planteo la clase Proyecto. Desde luego en cuanto a diseño este trabajo es… extraño pero en cuanto a aprender a programar en C++ es excelente, pues nuanca en mi vida pude ver tantas perrería en tan poco código.
Cabecera proyecto.h
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
| /*
* File: proyecto.h
* Author: Jonathan Gándara Alonso
*
* Created on 9 de abril de 2010, 15:48
*/
#include <string>
#include "fecha.h"
#include "investigador.h"
#include "listaInvestigadores.h"
#ifndef _PROYECTO_H
#define _PROYECTO_H
using namespace std; // para que pille la string
class Proyecto{
public:
Proyecto(string nom, Fecha inicio_p, Fecha fin_p, double presu);
~Proyecto();
string getNombre();
void setNombre(string nom);
string getDescripcion();
void setDescripcion(string desc);
string toString();
Fecha getInicio();
Fecha getFin();
void setInicio(Fecha a);
void setFin(Fecha a);
double getPresupuesto();
void setPresupuesto(double p);
Investigador getInvestigadorPrincipal();
void setInvPPal(Investigador &nuevo);
ListaInvestigadores investigadores;
private:
string nombre;
string descripcion;
double presupuesto;
Investigador investigadorPrincipal;
Fecha inicio;
Fecha fin;
};
#endif /* _PROYECTO_H */ |
Y la implementación del mismo:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
| /*
* File: proyecto.h
* Author: Jonathan Gándara Alonso
*
* Created on 9 de abril de 2010, 15:48
*/
#include <string>
#include "proyecto.h"
#include <iostream>
#include <sstream>
using namespace std;
Proyecto::Proyecto(string nom, Fecha inicio_p, Fecha fin_p, double presu){
nombre = nom;
inicio = inicio_p;
fin = fin_p;
presupuesto = presu;
descripcion = "";
}
Proyecto::~Proyecto(){
}
string Proyecto::getNombre(){
return nombre;
}
void Proyecto::setNombre(string n){
nombre = n;
}
string Proyecto::getDescripcion(){
return descripcion;
}
void Proyecto::setDescripcion(string de){
descripcion = de;
}
string Proyecto::toString(){
return "Nombre: "+nombre+"\n Descripción: "+descripcion+"\n Inicio: "+inicio.toString()+"\n Fin: "+fin.toString();
}
Fecha Proyecto::getInicio(){
return inicio;
}
Fecha Proyecto::getFin(){
return fin;
}
void Proyecto::setInicio(Fecha a){
inicio = a;
}
void Proyecto::setFin(Fecha a){
fin = a ;
}
double Proyecto::getPresupuesto(){
return presupuesto;
}
void Proyecto::setPresupuesto(double p){
presupuesto = p;
}
Investigador Proyecto::getInvestigadorPrincipal(){
return investigadorPrincipal;
}
void Proyecto::setInvPPal(Investigador &nuevo){
investigadorPrincipal = nuevo;
} |
Tagged with: C++ • Programación
abr 14
Para hacer la clase listaInvestigadores teníamos unos requerimientos un tanto especiales:
Interfaz:

La lista de investigadores (ListaInvestigadores) será dinámica, tal y como se ha expuesto ya.Cada posición contendrá un puntero a un objeto de la clase Investigador (los investigadores podrán referenciarse según su posición en la lista). En caso de que se necesite almacenar un nuevo investigador, será necesario reservar espacio para el nuevo puntero, crear el objeto y sólo entonces, enlazarlo. En caso de eliminar una posición, se podrá realizar el comportamiento que se desee: eliminar el objeto, reservar (menos) espacio, y copiar los punteros al nuevo espacio, o eliminar el puntero de la lista y llevar un control de las posiciones empleadas. En cualquier caso, deberá ser posible saber el número de investigadores en todo momento, y no deberá haber huecos en dicha lista.
En resument que con las funciones que nos aportan en la interfaz no es suficiente. Para simplificar el código y no tener que crear un objeto contenedor que contenga a los investigadores y permita la ordenación en la lista se ha modificado la clase Investigador Añadiendole dos nuevas funciones que permiten crear una lista simplemente enlazada de investigadores.
Para implementar la listainvestigadores, se ha recurrido como siempre a una cabecera sencilla como la que sigue, denominada listaInvestigadores.h:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
| /*
* File: listaInvestigadores.h
* Author: Jonathan Gándara Alonso
*
* Created on 7 de abril de 2010, 12:21
*/
/*
Según los requerimientos queremos una lista ordenada de punteros,
sin huecos, y tenemos que poder referirnos y/o accedera posiciones
concretas de la lista.
*/
#include <string>
#include "fecha.h"
#include "investigador.h"
#ifndef _LISTAINVESTIGADORES_H
#define _LISTAINVESTIGADORES_H
using namespace std;
class ListaInvestigadores{
public:
ListaInvestigadores();
/*Genera una lista de investigadores vacía*/
Investigador* get(int pos);
/*dado una posición de la lista nos retorna un investigador
en el caso de que esa posición no sea válida se devolverá un
puntero a null
*/
void insertar( Investigador* i);
/* En este caso insertaremos un investigador en la lista, para ello
el investigador se creará y se nos pasará para insertarlo en la lista.
*/
void eliminar( int pos);
/* Esta función se usa para eliminar un investigador que está en una
posición determinada de la lista. En el caso de que esa posición no
exista simplemente no haremos nada
*/
void set(int pos, Investigador* i);
/* Inserta un investigador en una posición determinada, si esta posición
se encuentra entre el máximo y el mínimo se desplazarán los investigadores
que tengan posiciones iguales o mayores. Si la posición es mayor que el máximo
Se colocará al final de la lista pues "no podemos tener huecos"
*/
~ListaInvestigadores();
/*En el destructor tenemos que eliminar toda la memoria reservada por
los elementos que pertenecen a esta lista*/
int size();
/*retorna el número actual de investigadores de la lista*/
string toString();
void operator += (Investigador &nuevo);
void operator -- (int i);
Investigador* operator [] (int i);
void listaTodos();
private:
/*Será útil cómodo y eficiente tener una variable para almacenar el número de
investigadores actual.*/
int numInvestigadores;
Investigador *inicio, *fin;
int masReciente;
};
#endif /* _LISTAINVESTIGADORESH */ |
Y aquí la implementación:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243
| /*
* File: listaInvestigadores.h
* Author: Jonathan Gándara Alonso
*
* Created on 7 de abril de 2010, 12:21
*/
#include "listaInvestigadores.h"
#include "investigador.h"
#include <iostream>
#include <sstream>
using namespace std;
ListaInvestigadores::ListaInvestigadores(){
/*Creamos la lista vacía*/
numInvestigadores =0;
// Es importante inicializar los punteros
inicio = fin = NULL;
masReciente =0;
}
Investigador* ListaInvestigadores::get(int pos){
/*Si la Posición no existe retornamos un puntero a null*/
if ( pos > numInvestigadores){
return NULL;
}else{
/*En caso contrario recorremos la lista hasta encontrar
Al investigador*/
Investigador *punt= inicio;
for ( int i=1; i <= pos; i++){
if ( i == pos){
return punt;
}else{
punt = punt->getSig();
}
}
}
}
void ListaInvestigadores::insertar( Investigador* i){
/*Insertamos un investigador*/
if ( numInvestigadores ==0){
inicio =fin = i;
}else{
/*Si la lista no está vacía lo insertamos al final*/
fin->setSig(i);
fin = i;
}
numInvestigadores ++;
masReciente =numInvestigadores;
}
void ListaInvestigadores::eliminar(int pos){
Investigador *aux, *punt=inicio;
if ( pos <= numInvestigadores && pos > 0){
if ( pos > 1 && pos < numInvestigadores){
for ( int i = 2; i <= pos; i++){
// llevamos el puntero por la posición anterior al que queremos eliminar
punt = punt->getSig();
}
aux = punt->getSig();
// saltamos el enlace del nodo a eliminar
punt->setSig(aux->getSig());
// liberamos la memoria usada por aux
delete aux;
}else{
/*si no está en el medio de la lista, puede que sea
el primero el último elemento o el único elemento de la lsita*/
if (pos == 1 && numInvestigadores ==1){
inicio = fin = NULL;
masReciente =0;
}else{
if ( pos ==1) {// si es el primero
aux = inicio;
inicio = inicio->getSig();
delete aux;
}
if ( pos == numInvestigadores){// si es el último
for ( int i = 2; i <= pos; i++ ){
// llevamos el puntero por la posición anterior al que queremos eliminar
punt = punt->getSig();
}
fin = punt;
punt = punt->getSig();
delete punt;
}
}
}// fin de la eliminación de casos especiales
numInvestigadores-- ;
}
// si la posición no se encuentra en nuestro rango de posiciones no hacemos nada
}
void ListaInvestigadores::set(int pos, Investigador* inv){
Investigador *aux, *punt,*nuevo;
punt=inicio;
if ( pos <= numInvestigadores && pos > 1 ){
for ( int i = 2; i <= pos; i++ ){
// llevamos el puntero por la posición anterior a donde queremos hacer la inserción
punt = punt->getSig();
}
aux = punt->getSig();
// introduzco el nuevo investigador en el medio
nuevo = inv;
punt->setSig(nuevo);
punt = punt->getSig();// avanzo hasta el nuevo investigador
punt->setSig(aux);
// actualizo el puntero de última inserción
numInvestigadores ++;
masReciente = pos;
}else{
if ( pos ==1){
aux = inv;
aux->setSig(inicio);
inicio = aux;
numInvestigadores ++;
masReciente =1;
}
}
}
ListaInvestigadores::~ListaInvestigadores(){
/*En el destructor de la clase liberamos la memoria utilizada*/
Investigador *aux;
if (numInvestigadores > 0){
aux = inicio;
while ( inicio != fin){
inicio = inicio->getSig();
delete aux;
aux = inicio;
}
delete fin; // liberamos la última posición
}
}
int ListaInvestigadores::size(){
return numInvestigadores;
}
string ListaInvestigadores::toString(){
string datos ="";
if ( numInvestigadores > 0){
Investigador *punt= inicio;
for ( int i = 1; i <= numInvestigadores; i++){
datos += punt->toString() + "\n";
punt= punt->getSig();
}
}
return datos;
}
void ListaInvestigadores::operator += (Investigador &nuevo){
Investigador *inve = new(nothrow) Investigador(nuevo.getNombre(),
nuevo.getApellidos(),
*nuevo.getFecha(),
nuevo.getCategoria(),
nuevo.getSalario());
this->insertar( inve);
}
void ListaInvestigadores::operator --(int i){
this->eliminar(this->masReciente);
}
Investigador* ListaInvestigadores::operator [] (int x){
return this->get(x);
}
void ListaInvestigadores::listaTodos(){
if ( size() >0){
Investigador *temp = inicio;
for ( int i = 1; i<= size() ; i++){
cout << *temp<<endl;
temp = temp->getSig();
}
cout << "Inserte un caracter para continuar"<<endl;
char c = '1';
cin >> c;
}else{
cout << " No existen investigadores que listar"<<endl<<endl<< "Inserte un caracter para continuar"<<endl;
char c = '1';
cin >> c;
}
} |
Tagged with: C++ • Programación