C++函数指针 当作形参时候 如何使用,参数如何传递,举例试用

#include <iostream>
#include <string>
using namespace std;

//虽然不能定义函数类型的形参,但是形参可以是指向函数的指针
bool lengthcompare(const string &a,const string &b)
{
    return a.size() < b.size()? true: false;
}

//等价定义
//string useBig(const string &s1,const string &s2,bool pf(const string &a,const string &b))//第三个形参是函数类型,自动转换成指向函数的指针
string useBig(const string &s1,const string &s2,bool (*pf)(const string &a,const string &b)) //直接定义成指向函数的指针
{

    //函数指针作形参时,进入到函数里面后赋值,取返回值
    string a("abcuopppppp");//改变a,b的长度,可见输出s1或者s2.
    string b("fsfasdwa");

    
    //函数指针三种等价调用
    //bool p = pf(a,b);
    //bool p = lengthcompare(a,b);
    bool p =(*pf)(a,b);
    
    if(p)
    {
        return s1;
    }
    else
    {
        return s2;
    }
}
int main() {

    string s1("我是s1");
    string s2("我是s2");

    string result;

    //直接把函数当实参用.函数自动转换成指向函数的指针
    result = useBig(s1,s2,lengthcompare);

    cout<<result<<endl;
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/wbscpp/p/12944091.html
今日推荐