函數類型(FuncType)和函數指針(FuncPointer)
函數指針: 指向函數的的指針,和普通的指針無本質區別
函數類型: 由函數返回值類型/函數參數類型決定,和函數名稱無關
例如:
對於函數: bool my_function(int a, const std::string& str)
函數類型(FuncType): bool(int, const std::string&)
函數指針FuncPointer: bool (*FuncPointer)(int, const std::string&)
函數類型和函數指針和函數參數
(1) 函數形參: 函數類型不可作爲形參(但是一般編譯器會將函數類型形參自動轉爲函數指針),函數指針可以作爲形參
例如:
void my_function2(FuncPointer fp) // OK
void my_function3(FuncType fn) ==編譯器轉爲==> void my_function3(FuncPointer fp)
(2) 函數作爲實參時,自動轉爲函數指針
如下示例:
#include <iostream>
typedef void(*FuncPointer)(const std::string& str);
typedef void(FuncType)(const std::string& str);
void func(const std::string& str)
{
std::cout << __FUNCTION__ << "==> " << str << std::endl;
}
void functype_test(const std::string& str, FuncType ft)
{
ft(str);
}
void funcpointer_test(const std::string& str, FuncPointer fp)
{
fp(str);
}
int main(int argc, char *argv[])
{
const std::string str1 = "test_function_type_as_function_pointer";
functype_test(str1, func);
const std::string str2 = "test_function_as_function_pointer";
funcpointer_test(str2, func);
return 0;
}
函數類型和函數指針和函數返回值
FuncPointer my_function4() // 返回函數指針 OK
FuncType my_function5() // 返回函數類型 Error
函數類型和函數指針定義
(1) 形式1
typedef bool FuncType(int a, const std::string& str) // 函數類型
typedef bool *(FuncPointer)(int a, const std::string& str) // 函數指針
(2) 形式2
typedef decltype(my_function) FuncType // 函數類型
typedef decltype(my_function)* FuncPointer // 函數指針 = 函數類型*
(3) 形式3
using FuncType=bool(int, const std::string&) // 函數類型
using FuncPointer=bool(*)(int, const std::string&) // 函數指針