我如何在外面引用 C++ 方法

how can i refence a c++ method outside?

本文关键字:C++ 方法 引用 在外面      更新时间:2023-10-16

说,我有一些类,MusicVideoPhoto,并有一个名为Control的类,Control有一个方法,centerlcall(char* fuction_name,char* json_para)fuction_name可以是MusicVideoPhoto的成员方法之一。 所以,我想从Controlcentercall函数调用成员方法。

class Contact {
 pubilc:
 Contact();
 void getallcontact(char* data);
 void changeContact(char* data);
 void addacontact(char* data);
};
class Music {
 public :
 Music();
 void getMusic(char* data);
 void addMusic(char* data);
 void playMusic(char* data);
}
class Video {
 public:
 Video();
 void getVideo(char* data);
 void addVideo(char* data);
}
class Photo {
 public:
 photo();
 void getPhoto(char* data);
}
class Control {
   public:
   Control();
   centerlcall(char* fuction_name,char* json_para){
      //check function_name is in video ,photo,music ,if in , call the method . 
   }
}

我该怎么做?Qt有帮助吗?

我想要的不是让usr调用Music的getMusic或其他方式,而是呼叫中心调用,并告诉centercall他想要调用什么方法,就像ajax一样。

函数指针就够了!以面向对象的方式拥有它!

class Stuff {
public:
   virtual ~Stuff();
   virtual void get(char* data) = 0;
};

class Music : public Stuff{
   public :
      Music();
      void get(char* data);
}
class Video : public Stuff {
   public:
      Video();
      void get(char* data);
}
class Photo : public Stuff {
   public:
      Photo();
      void get(char* data);
}

class Control {
   public:
      Control();
      void centerlcall(Stuff* hisStuff, char* json_para){
          hisStuff->get(/* whatever */);
      }
}

美丽。


"谢谢,我想用JNI这样的东西,每个类喜欢音乐都有注册方法,把注册的导出方法控制,但我不知道怎么写。"

class Control {
   public:
      Control();
      void centerlcall(Stuff* hisStuff, char* json_para){
          hisStuff->get(/* whatever */);
      }
      void registerStuff (Stuff* hisStuff) {  // <- It's that easy!
         // push it to a vector or a list or whatever data collection you want
      }
}

由于这些类没有任何共同点,因此您必须将要调用的函数保存在某处。请注意,C++不会为您执行此操作,则没有存储函数名称等元数据,您必须自己执行此操作,例如:

class Control {
   std::unordered_map<std::string,std::function<void(char*)>> functions;
   public:
   Control();
   centerlcall(char* fuction_name,char* json_para){
      functions[function_name](json_para);
   }
}

当然你还是要把相关函数加到映射中,也许你想的键不是函数名,而是对象名+函数名,...或者,您可以使用事件/信号库来执行此操作,而不是重新发明轮子,该库应为您提供适当的框架。

无关:请不要使用char*之类的东西,请改用std::string