C++函数类型和函数指针

函数类型(FuncType)和函数指针(FuncPointer) ios

函数指针: 指向函数的的指针,和普通的指针无本质区别函数

函数类型: 由函数返回值类型/函数参数类型决定,和函数名称无关指针

例如:code

对于函数: bool my_function(int a, const std::string& str)编译器

函数类型(FuncType): bool(int, const std::string&)string

函数指针FuncPointer: bool (*FuncPointer)(int, const std::string&)io

函数类型和函数指针和函数参数编译

(1) 函数形参:  函数类型不可做为形参(可是通常编译器会将函数类型形参自动转为函数指针),函数指针能够做为形参function

例如:class

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&)            // 函数指针

相关文章
相关标签/搜索