Foros del Web » Programación para mayores de 30 ;) » Programación General »

Herencia de Clases en C++

Estas en el tema de Herencia de Clases en C++ en el foro de Programación General en Foros del Web. Hola a todos! Estoy realizando una aplicación en la cual aparecen clases que heredan de otras clases y me surge un problema al hacer uso ...
  #1 (permalink)  
Antiguo 09/03/2005, 08:29
 
Fecha de Ingreso: octubre-2004
Ubicación: Cork (Irlanda)
Mensajes: 161
Antigüedad: 19 años, 6 meses
Puntos: 1
Herencia de Clases en C++

Hola a todos!

Estoy realizando una aplicación en la cual aparecen clases que heredan de otras clases y me surge un problema al hacer uso de los constructores.

Vereis, tengo las siguientes definiciones:

Código:
class claseA{
  public:
    claseA(); // constructor;
};

class claseB: public claseA{     // claseB deriva de claseA
  public:
    claseB(int p[]); // constructor;
};

class claseC: public claseB{     // claseC deriva de claseB
  public:
     claseC(int p[]); // constructor;
};
y las siguientes implementaciones:

Código:
claseA::claseA(){
}

claseB::claseB(int p[]){
}

claseC::claseC(int p[]){
}
Teóricamente creo que esto debería compilarse correctamente... pero me sale el siguiente error:

Código:
error C2512: 'B' : no appropriate default constructor available
¿Alguien podria decirme que estoy haciendo mal? Gracias.
  #2 (permalink)  
Antiguo 09/03/2005, 13:26
Avatar de Eternal Idol  
Fecha de Ingreso: mayo-2004
Ubicación: Lucentum
Mensajes: 6.192
Antigüedad: 20 años
Puntos: 74
El problema es por claseC, al no tener claseB un constructor por defecto no se pueden crear sus objetos, agrega claseB() { } y listo.
__________________
¡Peron cumple, Evita dignifica! VIVA PERON CARAJO
  #3 (permalink)  
Antiguo 09/03/2005, 17:58
 
Fecha de Ingreso: octubre-2004
Ubicación: Cork (Irlanda)
Mensajes: 161
Antigüedad: 19 años, 6 meses
Puntos: 1
Hola de nuevo, lo estoy haciendo más sencillo.

Ahora tengo estas definiciones, en el fichero misclases.h:

Código:
class claseA{
  public:
    claseA(); // constructor;
};

class claseB: public claseA{     // claseB deriva de claseA
  public:
    claseB(); // constructor;
};

class claseC: public claseB{     // claseC deriva de claseB
  public:
     claseC(); // constructor;
};
Y esta implementación en misclases.cpp:

Código:
#include "misclases.h"

claseA::claseA(){
}

claseB::claseB(){
}

claseC::claseC(){
}
Con esto ya tengo los constructores por defecto y no debe haber ningún problema al compilar... pues bien:

Código:
nafxcwd.lib(thrdcore.obj) : error LNK2001: unresolved external symbol __endthreadex
nafxcwd.lib(thrdcore.obj) : error LNK2001: unresolved external symbol __beginthreadex
Esto ya no parece un error propio del proyecto o algo parecido... digo yo...

A parte de ese código anterior tengo lo siguiente en el fichero prueba.cpp:

Código:
#include "misclases.h"

int main(int argc, char** argv){
  return 0;
};
Como vereis el programa no hace nada... solo está así para ver si compila bien...

Uso Microsoft Visual C++ 6.0 y el tipo de proyecto es Win32 console aplication... y el proyecto se llama prueba... (por si es de ayuda)
  #4 (permalink)  
Antiguo 09/03/2005, 20:01
 
Fecha de Ingreso: noviembre-2003
Ubicación: Mexico
Mensajes: 1.081
Antigüedad: 20 años, 5 meses
Puntos: 7
he aqui un ejemplito que tome de un tuto :
int main()
{

// Instantiate our wizard
WIZARD wizard("Merlin",50,40,30,70);

char *wizard_name = wizard.getName(); // Get the name
int life = wizard.getLife(); // Get the life
int spellPower = wizard.getSpellPower(); // Get the spell power

// Print it
cout << wizard_name << "'s life = " << life << "." << endl;
cout << wizard_name << "'s spell power = " << spellPower << "." << endl << endl;
return 0;
}






luego en el .h
#define MAX_PLAYER_NAME 25 // The maximum number of characters in a player's name

#include <stdlib.h>
#include <string.h>

// This will encompass attributes (variables, characteristics) that ALL players have
// for this tutorial
class PLAYER
{
public:

// Our constructors
PLAYER();
PLAYER(char *player_name, int L, int I, int S); // L == life
// I == intellect
// S == strength

/** Data Access Functions **/

char* getName() { return name; }

int getLife() { return life; }

/** End of Data Access Functions **/


private:

char name[MAX_PLAYER_NAME]; // The name of the player

int life; // The amount of "life" the player has -- Range is 0 - 1000
int intellect; // How "smart the player is -- Range is 0 - 100
int strength; // How "strong" the player is -- Range is 0 - 100

bool alive; // Is the player alive or dead

};



/*
Okay here is where the power of inheritance (deriving from classes is)
We are going to inherit the WIZARD class from the PLAYER class meaning "certain aspects
of the PLAYER class will exist in the WIZARD class as if the code was cut 'n paste
directly into the WIZARD class" -- Notice I said "certain aspects", depending on how we
inherit, differnt aspects (member variables, methods) will be accessible to us in
the WIZARD class

*/

// The single colon ':' signifies we are inheriting -- The "public" means that everything that
// is public to the PLAYER class will be public to the WIZARD class
class WIZARD : public PLAYER
{
public:

// Constructors
WIZARD();
WIZARD(char *player_name, int L, int I, int S, int SP); // L == life
// I == intellect
// S == strength
// SP == spellPower

/** Data Access Functions **/

int getSpellPower() { return spellPower; }

/** End of Data Access Functions **/

private:

int spellPower; // The power of the wizard's spell -- Range 0 - 100

};




y en la utilizacion:


#include "player.h"

// Our constructors ---

// Our default constructor will set the player name to NULL
// It will set life to 100 units and intellect and strength to 20 units
// Since we a creating a player, it's obviously alive
PLAYER::PLAYER():life(100),intellect(20),strength( 20),alive(true)
{
// Clear the name to NULL
memset(name,0,MAX_PLAYER_NAME);
}

// An overloaded constructor will set the name, life, strength and intellect of the
// player to values passed in
PLAYER::PLAYER(char *player_name, int L, int I, int S):life(L),intellect(I),strength(S),alive(true)
{
// Clear the name to NULL
memset(name,0,MAX_PLAYER_NAME);

if(player_name)
{
int len = strlen(player_name); // Get the length of the player name passed in

// If it's greater than the space we are allotting for player names
// cut it off
if(len >= MAX_PLAYER_NAME)
{
for(int i = 0; i < MAX_PLAYER_NAME; i++)
name[i] = player_name[i];

name[MAX_PLAYER_NAME - 1] = NULL;
}
else
strcpy(name,player_name); // Just copy over the player name
}

} // end of PLAYER::PLAYER(char *player_name, int L, int S, int I)


// Our WIZARD class default constructor -- This set the spellPower to a value of 10
// Everything else (like "life" for example) will get set by the default PLAYER constructor
// that WILL be called
WIZARD::WIZARD():spellPower(10) { /* do nothing */ }

// Now this is our constructor that takes parameters --
// To set the PLAYER variables (such as life), we HAVE to EXPLICTILY call the PLAYER's constructor
// Otherwise the default constructor for the PLAYER will get called and these variables WILL NOT get set
WIZARD::WIZARD(char *player_name, int L, int I, int S, int SP):PLAYER(player_name,L,I,S),spellPower(SP)
{
/* do nothing */
}


espero te sirva
  #5 (permalink)  
Antiguo 10/03/2005, 03:30
Avatar de Eternal Idol  
Fecha de Ingreso: mayo-2004
Ubicación: Lucentum
Mensajes: 6.192
Antigüedad: 20 años
Puntos: 74
Cita:
Iniciado por masterjail
Código:
nafxcwd.lib(thrdcore.obj) : error LNK2001: unresolved external symbol __endthreadex
nafxcwd.lib(thrdcore.obj) : error LNK2001: unresolved external symbol __beginthreadex
Este es un error de enlazado (link) y no de compilación, es muy probable que hayas elegido alguna opción no standard de C de las MFC. Si compilas desde linea de comandos con : cl misclases.cpp te generará el ejecutable sin problemas. Busca en las opciones del proyecto como quitar las MFC o crea uno nuevo sin las mismas.
__________________
¡Peron cumple, Evita dignifica! VIVA PERON CARAJO
  #6 (permalink)  
Antiguo 10/03/2005, 06:18
 
Fecha de Ingreso: octubre-2004
Ubicación: Cork (Irlanda)
Mensajes: 161
Antigüedad: 19 años, 6 meses
Puntos: 1
Gracias Eternal Idol, puedo generar el ejecutable desde la linea de comandos... ahora solo me falta ir probando para solucionar el anterior error
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 04:37.