函数指针(详细介绍)

  • 定义:

数组指针——是指向数组的指针——存放数组地址;

函数指针——是指向函数的指针——存放函数地址;

数组中——arr和&arr都是数组首元素地址;

函数中——函数名和&函数名都是函数的地址;

#include<iostream>
using namespace std;
int Add(int x, int y) {
	int z = x + y;
	return z;
}
int main() {
	int a = 10;
	int b = 20;
	cout << Add(10, 20) << endl;
	cout << Add << endl;;
	cout << &Add << endl;
	system("pause");
	return 0;
}

输出结果如下:

  • 函数指针的写法及调用:

函数返回值类型 (*p) (函数形参1数据类型,函数形参2数据类型)——此时的p就代表一个指向函数的指针;

#include<iostream>
using namespace std;
#include<string>
int Add(int x, int y) {
	int z = x + y;
	return z;
}
void printf(const char* str) {
	cout << str << endl;
}
int main() {
	int a = 10;
	int b = 20;
	int(*pa)(int, int) = Add;
	cout << (*pa)(10, 20) << endl;  //因为pa是地址,解引用*pa才是找到了函数Add
	void(*pc)(const char*) = printf;
	(*pc)("hello"); //不能写成cout<<(*pc)("hello")<<endl;因为函数就是打印函数
	system("pause");
	return 0;
}


 

  • 0
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值