给定以下两个typedef
:
typedef void (*pftype)(int);
typedef void ftype(int);
我知道第一个将 pftype
定义为指向一个函数的指针,该函数接受一个 int
参数并且不返回任何内容,第二个定义 ftype
作为一种函数类型,它接受一个 int
参数并且不返回任何内容。但是,我不明白第二个可能用于什么。
我可以创建一个匹配这些类型的函数:
void thefunc(int arg)
{
cout << "called with " << arg << endl;
}
然后我可以使用 each 创建指向该函数的指针:
int main(int argc, char* argv[])
{
pftype pointer_one = thefunc;
ftype *pointer_two = thefunc;
pointer_one(1);
pointer_two(2);
}
当使用函数类型时,我必须指定我正在创建一个指针。使用函数指针类型,我没有。两者都可以作为参数类型互换使用:
void run_a_thing_1(ftype pf)
{
pf(11);
}
void run_a_thing_2(pftype pf)
{
pf(12);
}
因此,函数类型有什么用处?函数指针类型是不是覆盖了case,做起来更方便?
最佳答案
除了您指出的用途(指针的基础类型或对函数的引用)之外,函数类型最常见的用途是在函数声明中:
void f(); // declares a function f, of type void()
可能需要使用 typedef
:
typedef void ft(some, complicated, signature);
ft f;
ft g;
// Although the typedef can't be used for definitions:
void f(some, complicated, signature) {...}
并作为模板参数:
std::function<void()> fn = f; // uses a function type to specify the signature
关于c++ - 函数类型用于什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13590084/