括号内的单个星号是什么"(*)"用C ++做什么?

时间:2014-05-12 18:17:05

标签: c++

我发现代码如下:

typedef std::map<std::string, Example*(*)()> map_type;

在搜索了一段时间后,我仍然无法弄清楚(*)运算符究竟是做什么的。有人有什么想法吗?

4 个答案:

答案 0 :(得分:7)

这里的parens用于强加优先权。类型

Example*(*)()

是指向函数的指针,返回指向Example的指针。

没有parens你会有

Example**()

这是一个返回指向Example指针的函数。

答案 1 :(得分:5)

这是用于声明指向函数(您的大小写)或数组的指针的语法。接受声明

typedef Example* (*myFunctionType)();

这将成为行

typedef std::map<std::string, myFunctionType> map_type;

完全等同于您提供的行。请注意,Example* (*myFunctionType)()Example* (*)()之间的区别仅在于省略了该类型的名称。

答案 2 :(得分:0)

这是函数指针声明。

typedef 表示std :: map将字符串映射到函数指针,接收 void 并返回示例*

您可以像这样使用它:

#include <string>
#include <map>

typedef  int Example;

Example* myExampleFunc() {
    return new Example[10];
};

typedef std::map<std::string, Example*(*)()> map_type;

int main() {

    map_type myMap;
    // initializing
    myMap["key"] = myExampleFunc;

    // calling myExampleFunc

    Example *example = myMap["key"]();

    return 0;
}

答案 3 :(得分:-1)

由于模板typedef:

,你可以在C ++ 11中使复杂的指针类型更容易混淆
template<typename T> using ptr = T*;

typedef std::map<std::string, ptr<Example*()>> map_type;