elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: Estamos en la red social de Mastodon


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación C/C++ (Moderadores: Eternal Idol, Littlehorse, K-YreX)
| | |-+  Problema al pasar funcion como parametro a un inicializador de clase [C++][ok]
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: Problema al pasar funcion como parametro a un inicializador de clase [C++][ok]  (Leído 6,774 veces)
<[(x)]>

Desconectado Desconectado

Mensajes: 215



Ver Perfil
Problema al pasar funcion como parametro a un inicializador de clase [C++][ok]
« en: 16 Abril 2012, 05:53 am »

Buenas estaba probando hacer un código y todo estupendo hasta el momento de compilar.

 Lo que pretendo es pasar la función MenssageArrival a mi clase Server de tipo ServerDosGame para, cuando el servidor este pueda ejecutar la función MenssageArrival externa a el.

   El error es el siguiente:
Código:
game.cpp: In member function ‘int Game::Start()’:
game.cpp:14: error: no matching function for call to ‘ServerDosGame::ServerDosGame(unsigned int&, unsigned int&, <unresolved overloaded function type>)’
DGS.hpp:24: note: candidates are: ServerDosGame::ServerDosGame(unsigned int&, unsigned int&, std::string (*)(unsigned int, std::string))
DGS.hpp:21: note:                 ServerDosGame::ServerDosGame(const ServerDosGame&)

La linea 14 de game.cpp seria:
Código
  1.  
  2. Server = new ServerDosGame(uInt_NumberOfPlayers, uInt_StateGame, MenssageArrival);
  3.  
siendo uInt_NumberOfPlayers, uInt_StateGame unsigned int y  MenssageArrival la siguiente funcion:
Código
  1. string MenssageArrival(unsigned int uInt_ID, string Str_Msg);

ServerDosGame es una clase en la cual defino su constructor de la siguiente manera:
Código
  1.   ServerDosGame(unsigned int & NumberOfPlayers, unsigned int & uInt_StateGame, string (FuncOfMsg)(unsigned int uInt_ID, string Str_Msg) );

Es la primera ves que trato con funciones de esta forma, ya probé un par de cosas pero nada funciono espero puedan ayudarme :)

Si es necesario que deje mas informacion para reaolver el problema q tengo...

Diganme :)


« Última modificación: 17 Abril 2012, 05:31 am por <[(x)]> » En línea

<[(x)]>
<[(x)]>

Desconectado Desconectado

Mensajes: 215



Ver Perfil
Re: Problema al pasar funcion como parametro de otra. a(b()); [C++]
« Respuesta #1 en: 16 Abril 2012, 21:17 pm »

hola de nuevo...

estuve cambiando las definiciones de
Código
  1. string (FuncOfMsg)(unsigned int uInt_ID, string Str_Msg)
por
Código
  1. string (*FuncOfMsg)(unsigned int uInt_ID, string Str_Msg)

y ahora paso a la función de la siguiente forma:

Código
  1. string (* SendMsg )(unsigned int uInt_ID, string Str_Msg);
  2.  
  3. SendMsg = MenssageArrival;
  4.  
  5. Server = new ServerDosGame(uInt_NumberOfPlayers, uInt_StateGame, SendMsg);

la definición de la función que paso esta intacto y la que recibe el puntero a función quedo así:
Código
  1. ServerDosGame(unsigned int & NumberOfPlayers, unsigned int & uInt_StateGame, string (*FuncOfMsg)(unsigned int uInt_ID, string Str_Msg) );

No logre solucionar el problema pero creo q esto es mas pavo solo q no logro hacer q coincidan los tipos? no entiendo del todo alguna manito por ahí ?.

Error de compilacion:
Código:
game.cpp:17: error: argument of type ‘std::string (Game::)(unsigned int, std::string)’ does not match ‘std::string (*)(unsigned int, std::string)’

...



« Última modificación: 16 Abril 2012, 21:20 pm por <[(x)]> » En línea

<[(x)]>
Beakman

Desconectado Desconectado

Mensajes: 190



Ver Perfil WWW
Re: Problema al pasar funcion como parametro a un inicializador de clase [C++]
« Respuesta #2 en: 17 Abril 2012, 03:18 am »

Buenas.
Copié el código en un archivo main.cpp. Y quedó así:
Código
  1. #include<iostream>
  2. using namespace std;
  3.  
  4. string MenssageArrival(unsigned int uInt_ID, string Str_Msg){
  5. string retorno;
  6. return retorno;
  7. }
  8.  
  9. class ServerDosGame{
  10. public:
  11. ServerDosGame( unsigned int & NumberOfPlayers, unsigned int & uInt_StateGame, string (*FuncOfMsg)(unsigned int uInt_ID, string Str_Msg) ){
  12. // hacer cosas
  13. }
  14. };
  15.  
  16. int main( int argc, char **argv ){
  17. unsigned int uInt_NumberOfPlayers, uInt_StateGame;
  18. ServerDosGame *Server = new ServerDosGame(uInt_NumberOfPlayers, uInt_StateGame, MenssageArrival);
  19. return 0;
  20. }

Esto me compila bien. No hay ningún error, podés intentar compilarlo vos.

Y hacé lo siguiente: poné todas las clases y funciones que tengas en un solo archivo main.cpp. Si por casualidad estás usando diferentes namespaces quitalos.
Y si estás usando algún entorno de desarrollo y te genera archivos objeto ( archivos .o ) Borralos y volvé a compilar.
Postea los errores que tengas.
En línea

<[(x)]>

Desconectado Desconectado

Mensajes: 215



Ver Perfil
Re: Problema al pasar funcion como parametro a un inicializador de clase [C++]
« Respuesta #3 en: 17 Abril 2012, 03:56 am »

 :D
    (pido disculpas por no aclarar que era desde otra clase)
    Gracias por responder. Si, eso lo pobre... solo que cunado lo pongo asi:

Código
  1. #include<iostream>
  2. using namespace std;
  3.  
  4. class ServerDosGame
  5. {
  6. public:
  7. string (*fMsg)(unsigned int uInt_ID, string Str_Msg);
  8.  
  9. ServerDosGame( unsigned int & NumberOfPlayers, unsigned int & uInt_StateGame, string (*FuncOfMsg)(unsigned int uInt_ID, string Str_Msg) )
  10. {
  11. fMsg = FuncOfMsg;
  12. }
  13.  
  14.  
  15. };
  16.  
  17.  
  18. class Game
  19. {
  20. public:
  21.  
  22. unsigned int uInt_NumberOfPlayers, uInt_StateGame;
  23. ServerDosGame *Server;
  24.  
  25. string MenssageArrival(unsigned int uInt_ID, string Str_Msg)
  26. {
  27. string retorno;
  28. return retorno;
  29. }
  30.  
  31.  
  32. int run()
  33. {
  34. Server = new ServerDosGame(uInt_NumberOfPlayers, uInt_StateGame, MenssageArrival);
  35. return 1;
  36. }
  37.  
  38.  
  39. };
  40.  
  41.  
  42. int main( int argc, char **argv )
  43. {
  44.  
  45. Game *game = new Game();
  46.  
  47. return game->run();
  48. }
Código:
g++ *.cpp
main.cpp: In member function ‘int Game::run()’:
main.cpp:33: error: no matching function for call to ‘ServerDosGame::ServerDosGame(unsigned int&, unsigned int&, <unresolved overloaded function type>)’
main.cpp:11: note: candidates are: ServerDosGame::ServerDosGame(unsigned int&, unsigned int&, std::string (*)(unsigned int, std::string))
main.cpp:7: note:                 ServerDosGame::ServerDosGame(const ServerDosGame&)
....
« Última modificación: 17 Abril 2012, 04:08 am por <[(x)]> » En línea

<[(x)]>
Beakman

Desconectado Desconectado

Mensajes: 190



Ver Perfil WWW
Re: Problema al pasar funcion como parametro a un inicializador de clase [C++]
« Respuesta #4 en: 17 Abril 2012, 04:13 am »

Citar
(pido disculpas por no aclarar que era desde otra clase)
Ah ! Ahora sí tiene sentido !.

Te faltó poner static en el método MenssageArrival.
Ese código quedaría así:
Código
  1. #include<iostream>
  2. using namespace std;
  3.  
  4. class ServerDosGame{
  5. public:
  6. string (*fMsg)(unsigned int uInt_ID, string Str_Msg);
  7. ServerDosGame( unsigned int & NumberOfPlayers, unsigned int & uInt_StateGame, string (FuncOfMsg)(unsigned int uInt_ID, string Str_Msg) ){
  8. fMsg = FuncOfMsg;
  9. }
  10. };
  11.  
  12. class Game{
  13. public:
  14. unsigned int uInt_NumberOfPlayers, uInt_StateGame;
  15. ServerDosGame *Server;
  16.  
  17. // string MenssageArrival(unsigned int uInt_ID, string Str_Msg){
  18. static string MenssageArrival(unsigned int uInt_ID, string Str_Msg){ // Debería ser así
  19. string retorno;
  20. return retorno;
  21. }
  22.  
  23. int run(){
  24. Server = new ServerDosGame(uInt_NumberOfPlayers, uInt_StateGame, MenssageArrival);
  25. return 1;
  26. }
  27. };
  28.  
  29. int main( int argc, char **argv ){
  30. Game *game = new Game();
  31. return game->run();
  32. }

Static es para poder acceder al método sin declarar una instancia de la clase. Ahora reparando en el código original te debería compilar bien.
En línea

<[(x)]>

Desconectado Desconectado

Mensajes: 215



Ver Perfil
Re: Problema al pasar funcion como parametro a un inicializador de clase [C++]
« Respuesta #5 en: 17 Abril 2012, 04:38 am »


   Perfecto.

      En la definición le puse static pero en la implementación si le ponía me saltaba que no existía dicha función.

      Después dice lo siguiente:
Código:
game.cpp: In static member function ‘static std::string Game::MenssageArrival(unsigned int, std::string)’:
game.cpp:48: error: cannot call member function ‘void Game::SetDefaultValues()’ without object
Game.hpp:21: error: invalid use of member ‘Game::uInt_StateGame’ in static member function
game.cpp:49: error: from this location

           xD ...

como accedo a las variable/funciones de la clase?
En línea

<[(x)]>
Beakman

Desconectado Desconectado

Mensajes: 190



Ver Perfil WWW
Re: Problema al pasar funcion como parametro a un inicializador de clase [C++]
« Respuesta #6 en: 17 Abril 2012, 05:06 am »

La definición es así:
Código
  1. static string MenssageArrival(unsigned int uInt_ID, string Str_Msg); // dentro de la clase
  2. string Game::MenssageArrival(unsigned int uInt_ID, string Str_Msg){ // fuera de la clase
  3. string retorno;
  4. return retorno;
  5. }

Si querés manipular las variables miembro de la clase creo que sería mejor pasarle un puntero del objeto que estás usando, en lugar de pasarle el método.
En línea

<[(x)]>

Desconectado Desconectado

Mensajes: 215



Ver Perfil
Re: Problema al pasar funcion como parametro a un inicializador de clase [C++]
« Respuesta #7 en: 17 Abril 2012, 05:30 am »

gracias.. creo q voy a probar con eso... jeje despues seguiré probando en próximos programas ya q en vb me dio buen resultado.
« Última modificación: 17 Abril 2012, 05:32 am por <[(x)]> » En línea

<[(x)]>
Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines