C ++ typedef声明

时间:2010-12-07 07:44:24

标签: c++ typedef

您能否解释一下以下几行的含义?

typedef int (*Callback)(void * const param,int s)

3 个答案:

答案 0 :(得分:6)

这意味着Callback是类型的新名称:指向函数的指针,该函数返回一个int并将两个参数类型为'const指向void'和'int'。

给定函数f

int f(void * const param, int s)
{
    /* ... */
}

Callback可用于存储指向f的指针:

Callback c = &f;

稍后可以通过指针调用函数f,而无需直接引用其名称:

int result = c(NULL, 0);

在通话时,名称f不会出现。

答案 1 :(得分:2)

它创建一个新的“别名”或名称,通过它您可以引用返回int的函数的指针并获取两个参数:void* const和int。然后,您可以创建该类型的变量,分配给它们,通过它们调用函数等,如下所示:

int fn(void * const param,int s) { ... }

Callback p;
p = fn;
int x = p(NULL, 38);

请注意,typedef并不真正创建新类型...为了重载解析,模板实例化等目的,每个等效的typedef都被解析为单个实数类型。

答案 2 :(得分:2)

它声明了一个函数类型:

// Set up Callback as a type that represents a function pointer
typedef int (*Callback)(void * const param,int s);

// A function that matches the Callback type
int myFunction(void* const param,int s)
{
    // STUFF
    return 1;
}

int main()
{
    // declare a variable and assign to it.
    Callback   funcPtr = &myFunction;
}
相关问题