[英]How to interpret “void(*)()”?
When I read the shared_ptr , I found a piece of code:当我阅读shared_ptr时,我发现了一段代码:
void(*)()
How to interpret it?如何解读它?
It is a pointer to a function type, which can be used for all the functions which have no arguments and returns void
.它是一个指向 function 类型的指针,可用于所有没有 arguments 并返回
void
的函数。
For example:例如:
void function_1() {}
void function_2() {}
void(*func_1_ptr)() = function_1; // or = &function_1;
void(*func_2_ptr)() = function_2; // or = &function_2;
Now func_1_ptr
holds the pointer to the function function_1
, and func_2_ptr
holds the pointer to function_2
.现在
func_1_ptr
持有指向 function function_1
的指针,而func_2_ptr
持有指向function_2
的指针。
You can make the type more intuitive by using
declaration.您可以
using
声明使类型更直观。
using FunPtrType = void(*)();
and now you could write现在你可以写了
FunPtrType func_1_ptr = function_1; // or = &function_1;
//Type identifier function
FunPtrType func_2_ptr = function_2; // or = &function_2;
This is the type of a pointer to a function, which takes no arguments and returns void
.这是指向 function 的指针的类型,它不接受 arguments 并返回
void
。
The asterisk in between an open-close parenthesis (*)
represents the declaration of a function-pointer.开闭括号
(*)
之间的星号表示函数指针的声明。 The left and right of this represent the return type and function arguments of the function that it will point to.这个的左右分别代表function的返回类型和function arguments。
So basically in your case:所以基本上在你的情况下:
void printHello()
{
std::cout<<"Hello";
}
void(*fPtr)() = printHello;
In C++ you can do the same using a better OOP way:在 C++ 中,您可以使用更好的 OOP 方式执行相同操作:
std::function<void()> fPtr = printHello;
fPtr();
You will have to include the functional
header您将必须包括
functional
header
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.