《我的第一本c++书》学习笔记:STL之函数的相关内容(一)

本文详细介绍了函数指针的声明与赋值方式,并通过实例演示了如何使用函数指针调用不同函数,展示了函数指针在条件判断场景中的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、函数指针的声明与赋值

首先,知道一个函数的函数名表示这个函数的入口地址。如果某个函数指针指向这个函数,则这个入口地址就是函数指针所指向的地址。

//声明一个函数
void PrintPass( int nScore );
//定义函数指针
void (*pPrintFunc)( int nScore );
定义函数指针时也可缩写为:

void (*pPrintFunc)( int );

定义多个同一类型的指针时,可以用typedef来简化:

typedef void (* PRINTFUNC )(int);
PRINTFUNC pFuncFailed;
PRINTFUNC pFuncPass;

这里定义了一种新的函数指针类型PRINTFUNC,表示函数指针类型可以指向一个参数为int,返回值为void的函数。


pPrintFunc = PrintPass;

将函数名传给函数指针,即将入口地址传给指针。


STL为了简化,提供了auto关键字。

利用auto作为函数指针的数据类型来声明一个函数指针。auto会自动定义这种类型。

auto pPrintFunc = PrintPass ;


二、用函数指针调用函数

// 3.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <iostream>

using namespace std;


void PrintPass( int& nScore )
{
	cout<<"分数是:"<<nScore<<" 恭喜通过考试"<<endl;
}
void PrintFailed( int& nScore )
{
	cout<<"分数是:"<<nScore<<" 没有通过考试"<<endl;
}
void PrintExcellent( int& nScore )
{
	cout<<"分数是:"<<nScore<<" 不错"<<endl;
}

int _tmain(int argc, _TCHAR* argv[])
{
	
	int nScore = 22 ;

	//定义函数指针
	void (*pPrintFunc)( int& );

	if ( nScore < 60 )
	{
		pPrintFunc = PrintFailed;
	}
	else if( nScore >= 60 && nScore < 100)
	{
		pPrintFunc = PrintPass;
	}
	else
	{
		pPrintFunc = PrintExcellent;
	}

	(*pPrintFunc)( nScore );


	return 0;
}

如果通过回调来实现,这是稍作修改的代码:

// 3.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <iostream>

using namespace std;


typedef void (* PRINTFUNC )(int&);

void PrintMessage( int nScore , PRINTFUNC pFunc )
{
	cout<<"==========="<<endl;
	(*pFunc)( nScore );
	cout<<"+++++++++++"<<endl;
}

void PrintPass( int& nScore )
{
	cout<<"分数是:"<<nScore<<" 恭喜通过考试"<<endl;
}
void PrintFailed( int& nScore )
{
	cout<<"分数是:"<<nScore<<" 没有通过考试"<<endl;
}
void PrintExcellent( int& nScore )
{
	cout<<"分数是:"<<nScore<<" 不错"<<endl;
}

int _tmain(int argc, _TCHAR* argv[])
{
	
	int nScore = 22 ;

	//定义函数指针
	PRINTFUNC pFunc;

	if ( nScore < 60 )
	{
		pFunc = PrintFailed;
	}
	else if( nScore >= 60 && nScore < 100)
	{
		pFunc = PrintPass;
	}
	else
	{
		pFunc = PrintExcellent;
	}

	PrintMessage( nScore, pFunc);


	return 0;
}

最后给出一个链接帮助以后查看: 点击打开链接

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值