Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/137.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 函数类型用于什么?_C++_Function_Function Pointers - Fatal编程技术网

C++ 函数类型用于什么?

C++ 函数类型用于什么?,c++,function,function-pointers,C++,Function,Function Pointers,给定以下两个typedefs: typedef void (*pftype)(int); typedef void ftype(int); 我知道第一个定义是pftype作为指向一个函数的指针,该函数接受一个int参数,但不返回任何内容,第二个定义是ftype作为一个函数类型,接受一个int参数,但不返回任何内容。然而,我不明白第二个可能被用来做什么 我可以创建与以下类型匹配的函数: void thefunc(int arg) { cout << "called with

给定以下两个
typedef
s:

typedef void (*pftype)(int);

typedef void ftype(int);
我知道第一个定义是
pftype
作为指向一个函数的指针,该函数接受一个
int
参数,但不返回任何内容,第二个定义是
ftype
作为一个函数类型,接受一个
int
参数,但不返回任何内容。然而,我不明白第二个可能被用来做什么

我可以创建与以下类型匹配的函数:

void thefunc(int arg)
{
    cout << "called with " << arg << endl;
}
使用函数类型时,我必须指定我正在创建指针。使用函数指针类型,我不需要。这两种类型均可作为参数类型互换使用:

void run_a_thing_1(ftype pf)
{
    pf(11);
}

void run_a_thing_2(pftype pf)
{
    pf(12);
}

因此,函数类型有什么用途?函数指针类型是否涵盖了这些情况,并且做得更方便?

以及您指出的用法(指针或函数引用的基本类型),函数类型最常见的用法是函数声明:

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
std::函数fn=f;//使用函数类型指定签名
< /代码> 

也考虑这个

template<typename T>
void f(T*);
模板
无效f(T*);

因为我们希望它接受函数指针,通过模式匹配,T成为函数类型。

我只想指出,
函数\u T*fptr…
函数\u T fptr…
更清晰。第一种形式表示它必须是指针类型,这比任何东西都清楚,包括名称
funcptr\t

@nhahtdh:问题是,为什么会有函数类型以及指向函数类型的指针?@nhahtdh:事实上,正如Mike所说,问题是关于函数类型的。我知道为什么存在指向函数类型的指针。主要是为了“美化”效果(使代码更易于阅读)。您可以键入您喜欢的任何内容(只要有效)。在这两个案例中,我不确定哪一个更好。看看这一个相关的问题/答案:很好的答案。我从来没有想过这样使用typedef。啊,关键是函数声明。它们(显然)不能在函数定义中使用。@Mark:的确,这值得一提。
template<typename T>
void f(T*);