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

本文探讨了C++中的函数类型和函数指针的概念。函数类型由其返回值和参数类型定义,而函数指针可以指向函数。在函数参数中,函数指针可以作为形参,但函数类型不能。当函数作为实参传递时,会自动转换为函数指针。此外,介绍了三种定义函数类型和函数指针的方式:typedef、decltype和using关键字。
摘要由CSDN通过智能技术生成

函数类型(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 <<
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值