具有包含另一个类的函数指针的映射的类
我想做的是拥有一个包含第二个类的函数指针映射的类,但第二个类的名称应该不重要(不能硬编码到第一个类中)我真的希望能够实现这不使用宏。我已经按照 learncpp.com 上的函数指针示例进行操作,但是当在类之间传递它们时,我真的迷失了!我的尝试如下:
#include <map>
class Class1;
typedef double(Class1::*memFunc)();
class Class1
{
private:
std::map<std::string, memFunc> funcMap;
public:
void addFunc(std::string funcName, memFunc function)
{
funcMap.insert(std::pair<std::string, memFunc>(funcName, function));
}
};
class MyClass
{
public:
MyClass()
{
//How do I add member function getValue() to Class1?
class1.addFunc("new function", getValue());
}
double getValue()
{
return 0;
}
private:
Class1 class1;
};
What I wish to do is have a class that contains a map of function pointers of a second class, but the name of the second class should not matter (cannot be hard coded into the first class) I would really like to be able to implement this WITHOUT using macros. I have followed the examples from learncpp.com on function pointers, but when passing them between classes I am really lost! My attempt is below:
#include <map>
class Class1;
typedef double(Class1::*memFunc)();
class Class1
{
private:
std::map<std::string, memFunc> funcMap;
public:
void addFunc(std::string funcName, memFunc function)
{
funcMap.insert(std::pair<std::string, memFunc>(funcName, function));
}
};
class MyClass
{
public:
MyClass()
{
//How do I add member function getValue() to Class1?
class1.addFunc("new function", getValue());
}
double getValue()
{
return 0;
}
private:
Class1 class1;
};
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
类的名称是函数指针类型的一部分,函数指针成为映射类型的一部分,映射类型又成为 MyClass 的一部分。根据“不能硬编码”的要求有多强,也许模板就足够了?
The name of the class is a part of the type of the function pointer, which becomes part of the map's type, which becomes part of MyClass. Depending on how strong is the requirement "cannot be hard coded", perhaps a template would be sufficient?