c++ - 调用 C++ 方法指针

标签 c++ pointers c++11

我有以下示例 C++ 程序,它隐藏了指向类中方法的指针。调用该方法时出现编译器错误。

10     class Foo
11     {
12         void set_parm1(string) {}
13         void set_parm2(string) {}
14
15         typedef void (Foo::*set_func_t)(string);
16         struct Bar
17         {
18             string value;
19             set_func_t set_func;
20         };
21
22         map<string, Bar> parameter;
23
24         public:
25         Foo();
26         void set_value(string key, string value);
27     };
28
29     Foo::Foo()
30     {
31         Bar  temp;
32
33         temp.value = "value1";
34         temp.set_func = &Foo::set_parm1;
35         parameter["param1"] = temp;
36
37         temp.value = "value2";
38         temp.set_func = &Foo::set_parm2;
39         parameter["param1"] = temp;
40     }
41
42     void
43     Foo::set_value(string key, string value)
44     {
45         Bar temp;
46
47         temp = parameter[key];
48         this->*temp.set_func(value);
49     }

问题:

  1. 第 48 行编译错误

    ./test.cc: In member function 'void Foo::set_value(std::string, std::string)': ./test.cc:51:35: error: must use '.*' or '->*' to call pointer-to-member function in 'temp.Foo::Bar::set_func (...)', e.g. '(... ->* temp.Foo::Bar::set_func) (...)'

  2. 我要 set_func() (指向 set_parm1()set_parm2() )更新 parmX 的值在 map 本身。我有可能得到 Bar.value 的地址吗? (第 33 行)存储在 map 参数中,因此我可以将其传递给 set_func()

    如果否,那么我的下一个选项是什么,在 map 中存储指向“Bar”的指针,而不是 Bar 的拷贝。基本上使用 map<string, Bar *> .

  3. 只是坚持使用 STL(不使用 boost 库),是否有将 ptr 保存到结构/类与将整个对象存储在 map 中的指南。 (当然,这是假设结构/类本身没有指针,也就是存储整个对象时不需要深拷贝)。

谢谢你,
艾哈迈德。

最佳答案

对于1:你需要把它放在括号里:

(this->*temp.set_func)(value);

对于 2:您可以获取 temp.value 的地址(您可能指的是 Bar.value?),但这将毫无用处,因为它是一个临时变量,因此地址在 Foo 的构造函数完成后无效。

对于 3:我不太确定你的意思。您可以使用 std::shared_ptr 等。阿尔。如果您想避免复制大型/昂贵的对象或其他方式(如移动语义)来减少开销,但恐怕没有通用的答案。

关于c++ - 调用 C++ 方法指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20958815/

相关文章:

c# - 使用socket编程连接SqlServer

c - 二维数组和指针

c - 结构中的枚举; c的新手

c++11 - Const 引用 VS move 语义

c++ - 为什么在定义默认值时 boost::program_options 抛出有关必需参数的错误

c++ - 如何从 C++ 返回 char ** 并使用 ctypes 将其填充到 Python 列表中?

c++ - 我想仅使用递归将字符 "a"替换为字符 "z"

c - 变量 'pminutes' 未初始化就被使用

c++ - 以 std::string 为键的最有效关联容器?

C++ lambda 表达式 : captured pointer to STL container changing address after pop?