Problema al pasar funcion como parametro a un inicializador de clase [C++][ok]

Iniciado por <[(x)]>, 16 Abril 2012, 05:53 AM

0 Miembros y 1 Visitante están viendo este tema.

<[(x)]>

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:
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 (cpp) [Seleccionar]

Server = new ServerDosGame(uInt_NumberOfPlayers, uInt_StateGame, MenssageArrival);

siendo uInt_NumberOfPlayers, uInt_StateGame unsigned int y  MenssageArrival la siguiente funcion:
Código (cpp) [Seleccionar]
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 (cpp) [Seleccionar]
  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 :)
<[(x)]>

<[(x)]>

#1
hola de nuevo...

estuve cambiando las definiciones de
Código (cpp) [Seleccionar]
string (FuncOfMsg)(unsigned int uInt_ID, string Str_Msg) por
Código (cpp) [Seleccionar]
string (*FuncOfMsg)(unsigned int uInt_ID, string Str_Msg)

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

Código (cpp) [Seleccionar]
string (* SendMsg )(unsigned int uInt_ID, string Str_Msg);

SendMsg = MenssageArrival;

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 (cpp) [Seleccionar]
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:
game.cpp:17: error: argument of type 'std::string (Game::)(unsigned int, std::string)' does not match 'std::string (*)(unsigned int, std::string)'


...

<[(x)]>

Beakman

Buenas.
Copié el código en un archivo main.cpp. Y quedó así:
Código (cpp) [Seleccionar]
#include<iostream>
using namespace std;

string MenssageArrival(unsigned int uInt_ID, string Str_Msg){
string retorno;
return retorno;
}

class ServerDosGame{
public:
ServerDosGame( unsigned int & NumberOfPlayers, unsigned int & uInt_StateGame, string (*FuncOfMsg)(unsigned int uInt_ID, string Str_Msg) ){
// hacer cosas
}
};

int main( int argc, char **argv ){
unsigned int uInt_NumberOfPlayers, uInt_StateGame;
ServerDosGame *Server = new ServerDosGame(uInt_NumberOfPlayers, uInt_StateGame, MenssageArrival);
return 0;
}


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.

<[(x)]>

 :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 (cpp) [Seleccionar]
#include<iostream>
using namespace std;

class ServerDosGame
{
public:
string (*fMsg)(unsigned int uInt_ID, string Str_Msg);

ServerDosGame( unsigned int & NumberOfPlayers, unsigned int & uInt_StateGame, string (*FuncOfMsg)(unsigned int uInt_ID, string Str_Msg) )
{
fMsg = FuncOfMsg;
}


};


class Game
{
public:

unsigned int uInt_NumberOfPlayers, uInt_StateGame;
ServerDosGame *Server;

string MenssageArrival(unsigned int uInt_ID, string Str_Msg)
{
string retorno;
return retorno;
}


int run()
{
Server = new ServerDosGame(uInt_NumberOfPlayers, uInt_StateGame, MenssageArrival);
return 1;
}


};


int main( int argc, char **argv )
{

Game *game = new Game();

return game->run();
}

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&)

....
<[(x)]>

Beakman

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 (cpp) [Seleccionar]
#include<iostream>
using namespace std;

class ServerDosGame{
public:
string (*fMsg)(unsigned int uInt_ID, string Str_Msg);
ServerDosGame( unsigned int & NumberOfPlayers, unsigned int & uInt_StateGame, string (FuncOfMsg)(unsigned int uInt_ID, string Str_Msg) ){
fMsg = FuncOfMsg;
}
};

class Game{
public:
unsigned int uInt_NumberOfPlayers, uInt_StateGame;
ServerDosGame *Server;

// string MenssageArrival(unsigned int uInt_ID, string Str_Msg){
static string MenssageArrival(unsigned int uInt_ID, string Str_Msg){ // Debería ser así
string retorno;
return retorno;
}

int run(){
Server = new ServerDosGame(uInt_NumberOfPlayers, uInt_StateGame, MenssageArrival);
return 1;
}
};

int main( int argc, char **argv ){
Game *game = new Game();
return game->run();
}


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.

<[(x)]>


  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:
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?
<[(x)]>

Beakman

La definición es así:
Código (cpp) [Seleccionar]
static string MenssageArrival(unsigned int uInt_ID, string Str_Msg); // dentro de la clase
string Game::MenssageArrival(unsigned int uInt_ID, string Str_Msg){ // fuera de la clase
string retorno;
return retorno;
}


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.

<[(x)]>

gracias.. creo q voy a probar con eso... jeje despues seguiré probando en próximos programas ya q en vb me dio buen resultado.
<[(x)]>