我如何在外面引用 C++ 方法
how can i refence a c++ method outside?
说,我有一些类,Music
,Video
,Photo
,并有一个名为Control
的类,Control
有一个方法,centerlcall(char* fuction_name,char* json_para)
,fuction_name
可以是Music
,Video
,Photo
的成员方法之一。 所以,我想从Control
的centercall
函数调用成员方法。
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
。
相关文章:
- 为不同配置设置MSVC_RUNTIME_LIBRARY的正确方法是什么
- 通过方法访问结构
- 最小硬币更换问题(自上而下方法)
- C++为构建时间获取QDateTime的可靠方法
- 在C#中处理C++指针而不使用unsafe的最佳方法
- 处理多个异常集合的C++方法
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 有什么方法可以遍历结构吗
- 当类在C++中定义时,有什么方法可以"register"类吗?
- 在C++中,将大的无符号浮点数四舍五入为整数的最佳方法是什么
- 实现无开销push_back的最佳方法是什么
- 使用std::函数映射对象方法
- 有符号的int和int-有没有一种方法可以在C++中区分它们
- C++从另一个类访问公共静态向量的正确方法是什么
- C++优先级队列,按对象的唯一指针的特定方法升序排列
- 没有为自己的结构调用列表推回方法
- 有没有什么方法可以使用一个函数中定义的常量变量,也可以由c++中同一程序中的其他函数使用
- 在类定义之后定义一个私有方法
- 枚举环境变量的惯用C++14/C++17方法
- 初始化具有非默认构造函数的std::数组项的更好方法