[英]How to interpret “void(*)()”?
它是一个指向 function 类型的指针,可用于所有没有 arguments 并返回void
的函数。
例如:
void function_1() {}
void function_2() {}
void(*func_1_ptr)() = function_1; // or = &function_1;
void(*func_2_ptr)() = function_2; // or = &function_2;
现在func_1_ptr
持有指向 function function_1
的指针,而func_2_ptr
持有指向function_2
的指针。
您可以using
声明使类型更直观。
using FunPtrType = void(*)();
现在你可以写了
FunPtrType func_1_ptr = function_1; // or = &function_1;
//Type identifier function
FunPtrType func_2_ptr = function_2; // or = &function_2;
这是指向 function 的指针的类型,它不接受 arguments 并返回void
。
开闭括号(*)
之间的星号表示函数指针的声明。 这个的左右分别代表function的返回类型和function arguments。
所以基本上在你的情况下:
void printHello()
{
std::cout<<"Hello";
}
void(*fPtr)() = printHello;
在 C++ 中,您可以使用更好的 OOP 方式执行相同操作:
std::function<void()> fPtr = printHello;
fPtr();
您将必须包括functional
header
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.