/*
Date: 05/03/21 17:44
Description: 指向函数的指针
用typedef简化函数指针的定义
指向函数的指针的初始化和赋值
通过指针调用函数
函数指针形参
返回指向函数的指针
指向重载函数的指针
*/
#include<iostream>
#include<vector>
#include<cstring>
using namespace std;
typedef bool (*cmpFcn)(const string &,const string &);
typedef int (*PF)(int *,int);
bool lengthCompare(const string &s1,const string &s2)
{
return s1.size() == s2.size();
}
string::size_type sumLength(const string &s1,const string &s2)
{
return s1.size()+s2.size();
}
bool cstringCompare(char *s1,char *s2)
{
return strlen(s1) == strlen(s2);
}
void useBigger(const string &s1,
const string &s2,
bool (*pf)(const string &,const string &))
{
cout<<pf(s1,s2)<<endl;
}
int demo(int *p,int a)
{
return 12;
}
// ff是一个函数,有一个形参x,返回结果是一个函数指针int(*)(int *,int)
//int (*ff(int x))(int *,int)
PF ff(int x)
{
cout<<x<<endl;
return demo;
}
void ff(vector<double> vec)
{
cout<<"ff(vector<double> vec)"<<endl;
}
void ff(unsigned int x)
{
cout<<"ff(unsigned int x)"<<endl;
}
int main()
{
// void (*pf5)(int) = &ff; [Error] no matches converting function 'ff' to type 'void (*)(int)'
void (*pf8)(unsigned int) = &ff;
// double (*pf6)(vector<double>) = &ff; [Error] no matches converting function 'ff' to type 'double (*)(class std::vector<double>)'
void (*pf7)(vector<double>) = &ff;//可行
int a = 5;
int *pa;
cmpFcn pf4 = lengthCompare;
useBigger("hi","function",lengthCompare);//函数的名称就是指向函数的指针
cout<<ff(2)(&a,a)<<endl;
//pf是一个指针,指向函数的指针:函数的类型
//pf是一个局部变量
// bool (*pf)(const string &,const string &);
// bool (*pf2)(const string &,const string &);
// bool (*pf3)(const string &,const string &);
cmpFcn pf;
cmpFcn pf2;
cmpFcn pf3;
pf2 = lengthCompare;
// pf3 = sumLength; //下面这两种都是不可以的,指针与函数类型不匹配
// pf3 = cstringCompare;
// pf = &lengthCompare;
pf = lengthCompare;
pa = &a;
cout<<lengthCompare("hello","pointer")<<endl;
cout<<(*pf)("hello","pointer")<<endl;
cout<<(*pf2)("hello","point")<<endl;
cout<<*pa<<endl;
return 0;
}
c++学习-基础-指向函数的指针
最新推荐文章于 2021-05-20 04:31:35 发布