谁能帮我解释一下在C++中使用typedef?

Min*_*ing 3 c++ typedef

我对书中的这段代码很困惑:

typedef int (*healthCalcFunc) (const GameCharacter&)
Run Code Online (Sandbox Code Playgroud)

我明白,这 typedef double* PDouble意味着这个词PDouble可以用来声明一个指针double.

但我无法弄清楚其含义 typedef int (*healthCalcFunc) (const GameCharacter&)

有人能帮我解释一下吗?

提前致谢

:)

Jer*_*fin 5

在这种情况下,运算符优先级往往会妨碍.

这创建了一个别名(命名healthCalcFunc),类型为"指向函数的指针,该函数将const GameCharacter作为参数并返回一个int".

  1. int:返回类型
  2. (*healthCalcFunc):指向函数的指针 - 必须在parens中绑定*到名称而不是前面的名称int,这将声明一个函数返回指针而不是指向函数的指针.
  3. (const GameCharacter &):这将指向的函数类型的参数列表.


Naw*_*waz 5

typedef int (*healthCalcFunc) (const GameCharacter&);
Run Code Online (Sandbox Code Playgroud)

它引入了一个名为healthCalcFunc的名称,用于描述函数指针的类型,获取一个类型的参数const GameCharacter&并返回一个int.

所以这意味着,如果你有一个函数:

int some_function(const GameCharacter&)
{
    //...
}
Run Code Online (Sandbox Code Playgroud)

然后你可以创建一个指针对象,它将上述函数指向:

healthCalcFunc pfun = some_function;
Run Code Online (Sandbox Code Playgroud)

然后用来pfun代替some_function:

some_function(args);  /normal call

pfun(args);  //calling using function pointer 
             //it is exactly same as the previous call
Run Code Online (Sandbox Code Playgroud)

这种方法的好处是你可以传递pfun(或some_function)到其他功能:

void other_function(healthCalcFunc pfun)
{
    //..
    pfun(args); //invoke the function!
    //..
}

healthCalcFunc pfun = some_function;

other_function(some_function);  
other_function(pfun); 
Run Code Online (Sandbox Code Playgroud)

这里other_function将使用函数指针来调用该函数.这样,下次你可以传递另一个匹配函数签名的函数other_function,other_function并将调用另一个函数.