函数与指针

函数指针

1. 函数指针的使用

 bool lengthCompare(const string& str1, const string& str2)
 {
     if (str1 == str2)
         return true;
     return false;
 }
 ​
 int main()
 {   
     /*
         函数指针定义:函数类型(返回值类型和形参类型共同决定)
         函数类型 bool(const string &, const string &)
     */
     bool (*pf1)(const string &, const string &);
     bool (*pf2)(const string &, const string &);
 ​
     //函数赋值,函数名作为一个值使用,该函数自动转成指针
     //等价赋值
     pf1 = lengthCompare;
     pf2 = &lengthCompare;
     //函数引用
     //等价调用
     bool b1 = pf1("hello", "goodbye");
     bool b2 = (*pf1)("hello", "goodbye");
     bool b3 = lengthCompare("hello", "goodbye");
 ​
     cout << "b1 :" << b1 << endl;
     cout << "b2 :" << b2 << endl;
     cout << "b3 :" << b3 << endl;
     return 0;
 }

2. 重载函数指针

 void ff(int*);
 void ff(unsigned int);
 ​
 int main()
 {   
     void (*pf1)(unsigned int) = ff;
     //void (*pf2)(int) = ff;    //形参不匹配
     //double (*pf3)(int*) = ff;//返回值类型不匹配
     return 0;
 }

3. 函数指针形参

 //自动转成函数指针
 void useBigger(const string& s1, const string& s2,
     bool p(const string&, const string&)) {};
 //手动定义为函数指针
 void useBigger(const string& s1, const string& s2,
     bool (*p)(const string&, const string&)) {};
 ​
 int main()
 {   
     string s1 = "tom";
     string s2 = "jam";
     useBigger(s1, s2, lengthCompare);
     return 0;
 }
 ​
 //Func和Func2是函数类型
 typedef bool Func(const strings,const strings);
 typedef decltype(lengthCompare)Func2;//等价的类型
 //FuncP和FuncP2是指向函数的指针
 typedef bool(*FuncP)(const string&,const strings);
 typedef decltype(1engthCompare)*FuncP2;//等价的类型
     
 /*
   Func和Func2是函数类型,而FuncP和FuncP2是指针类型。
   decltype返回函数类型,此时不会将函数类型自动转换成指针类型。
   因为decltype的结果是函数类型,所以只有在结果前面加上*才能得到指针。
   在第一条语句中,编译器自动地将Func表示的函数类型转换成指针。
 */

4. 返回指向函数的指针

不能返回一个函数,但是能返回指向函数类型的指针

 using F=int(int*,int);//F是函数类型,不是指针
 using PE=int(*)(int*,int);//PF是指针类型
 //#1 指针类型
 PF f1(int);//正确:PF是指向函数的指针,f1返回指向函数的指针
 //#2 函数类型
 F f1(int);//错误:F是函数类型,f1不能返回一个函数
 F *f1(int);//正确:显式地指定返回类型是指向函数的指针当然,我们也能用下面的形式直接声明f1:
 //#3 直接
 int(*f1(int))(int*,int);  
 //f1有形参列表,所以f1是个函数;
 //f1前面有*,所以f1返回一个指针;
 //进一步观察发现,指针的类型本身也包含形参列表,因此指针指向函数,该函数的返回类型是int。
 //#4 尾置
 auto fl(int)->int (*)(int*,int);

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值