Mar*_*ark 14 c++ function-pointers function
给出以下两个typedefs:
typedef void (*pftype)(int);
typedef void ftype(int);
Run Code Online (Sandbox Code Playgroud)
我理解第一个定义pftype为一个函数的指针,它接受一个int参数并且什么都不返回,第二个定义ftype为一个函数类型,它接受一个int参数并且什么都不返回.但是,我不了解第二个可能用于什么.
我可以创建一个匹配这些类型的函数:
void thefunc(int arg)
{
cout << "called with " << arg << endl;
}
Run Code Online (Sandbox Code Playgroud)
然后我可以使用每个创建指向此函数的指针:
int main(int argc, char* argv[])
{
pftype pointer_one = thefunc;
ftype *pointer_two = thefunc;
pointer_one(1);
pointer_two(2);
}
Run Code Online (Sandbox Code Playgroud)
使用函数类型时,我必须指定我正在创建一个指针.使用函数指针类型,我没有.两者都可以互换使用作为参数类型:
void run_a_thing_1(ftype pf)
{
pf(11);
}
void run_a_thing_2(pftype pf)
{
pf(12);
}
Run Code Online (Sandbox Code Playgroud)
因此,功能类型有什么用?函数指针类型不包括案例,并且更方便吗?
除了指出的用法(指针的基础类型或函数的引用)之外,函数类型的最常见用途是函数声明:
void f(); // declares a function f, of type void()
Run Code Online (Sandbox Code Playgroud)
谁可能想要使用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) {...}
Run Code Online (Sandbox Code Playgroud)
并作为模板参数:
std::function<void()> fn = f; // uses a function type to specify the signature
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
677 次 |
| 最近记录: |