C++ 函数指针

本文详细介绍了C++中函数指针的概念、语法、使用方式以及如何将其作为参数传递给其他函数,包括如何通过指针调用函数,并讨论了函数指针的初始化和赋值规则。

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

             函数指针是指向函数的指针,像其它指针一样,函数指针也指向某个特定的类型。函数类型由返回值和其形参表决定,与函数名无关。

            bool (*pf)(const string &, const string &);  这个语句将 pf 声明为指向函数的指针,它所指向的函数带有两个 const string& 类型的形参和 bool 类型的返回值。

            函数指针类型相当地冗长。使用 typedef 为指针类型定义同义词,可将函数指针的使用大大简化:

           typedef bool (*cmpFcn)(const string &, const string &);  该定义表示cmpFunc是一种指向函数的指针类型的名字。该指针类型为“指向返回 bool 类型并带有两个 const string 引用形参的函数的指针”。在要使用这种函数指针类型时,只需直接使用 cmpFcn 即可,不必每次都把整个类型声明全部写出来。

  假设有函数: 

     // compares lengths of two strings 
     bool lengthCompare(const string &, const string &); 

 cmpFcn pf1 = 0;             // ok: unbound pointer to function 
         cmpFcn pf2 = lengthCompare; // ok: pointer type matches function's  type

   此时,直接引用函数名等效于在函数名上应用取地址操作符: 
      cmpFcn pf1 = lengthCompare; 
      cmpFcn pf2 = &lengthCompare; 
 
函数指针只能通过同类型的函数或函数指针或 0 值常量表达式进行初始化或赋值。将函数指针初始化为 0,表示该指针不指向任何函数。

通过指针调用函数,可以不使用解引用操作符,直接通过指针调用函数:

      cmpFcn pf = lengthCompare; 
      lengthCompare("hi", "bye"); // direct call 
      pf("hi", "bye");            // equivalent call: pf1 implicitly dereferenced 
      (*pf)("hi", "bye");         // equivalent call: pf1 explicitly dereferenced 


可以将函数指针作为形参传递给调用函数, 这种形参可以用以下两种编写形式:

      // third parameter is a function type and is automatically treated as a pointer to 

      void useBigger(const string &, const string &, 
                    bool(const string &, const string &)); 
      // equivalent declaration: explicitly define the parameter as a pointer to function 
      void useBigger(const string &, const string &, 
                    bool (*)(const string &, const string &));


  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值