取消引用时奇怪的星号使用



我今天遇到了看起来像这样的代码:

result = (this->*(*c))(&param)

让我感到困惑的主要部分是this->*(*c)箭头(->)和我们正在访问的变量名称(c)之间使用星号运算符是什么意思。

你在这里有一个你不经常看到的运算符。

->*是单个运算符。它是.*的基于指针的对应项,并且是成员访问运算符。

如果您有一个对象要使用成员(例如函数),但不知道具体成员(它存储在变量中),则使用它。

让我们把它分开:

this      // object to work on
->*       // member access operator
(*c)      // dereference pointer pointing to member function (c is a pointer-to-pointer)
(&param)  // call member function stored in c on this passing &param to the function

另请参阅:http://en.cppreference.com/w/cpp/language/operator_member_access

编辑:这篇文章还包含对这里发生的事情的良好解释:https://stackoverflow.com/a/6586248/1314789

表达式的解析树如下:

                         =
                  /            
               result     function call
                            /       
                          ->*        &
                         /          |
                       this   *    param
                              |
                              c
由于无聊的

语法原因,括号是必要的。

最新更新