函数指针(需精确匹配)

使用函数指针

取址和使用都有两种方式

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

bool lengthCompare(const string&, const string&){}
bool (*pf)(const string&, const string&);

int main() {

   pf = lengthCompare;
   pf = &lengthCompare;

    (*pf)("hello", "goodbye");
    pf("hello", "goodbye");

    return 0;
}

必须精确匹配,不允许差不多,不允许转换

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


string::size_type sumLength(const string &, const string &){}

bool lengthCompare(const char *, const char *){}

bool (*pf)(const string&, const string&);

int main() {

   pf = sumLength;  //xxx ,返回类型不匹配
   pf = lengthCompare; //xxx, 形参类型不匹配


    return 0;
}

(重载函数)的指针也必须精确匹配

注意精确匹配和最佳匹配不是一个意思,是禁止类型转换的

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


void ff(int *)
{}

void ff(unsigned int)
{}

int main() {

   void (*pf1)(unsigned int) = ff; //精确匹配
   void (*pf2)(int) = ff; //xxx,找不到精确匹配
   double (*pf3)(unsigned int) = ff; //xxx,找不到精确匹配
   
    return 0;
}

函数指针作为形参

有两种形式:一种函数类型,一种函数指针类型

void useBigger(const string& s1, const string& s2, bool pf(const string &s1, const string &s2));   //函数类型会转化为指针
void useBigger(const string& s1, const string& s2, bool (*pf)(const string &s1, const string &s2));

函数指针作为返回值

和数组指针一样,都是复杂类型,作为返回值较复杂。

1.使用using

注意出现一种叫函数类型的东西。

using F = int(int*, int);   //函数类型
using PF = int (*)(int*, int);  //函数指针类型

PF f(int);

F f(int);   //xxx,不能返回一个函数
F* f(int);

2.使用原生法

int (*f(int))(int *, int);   //返回类型的是int (*)(int *, int)

3.使用尾置类型

auto f(int) -> int (*)(int *, int);

猜你喜欢

转载自blog.csdn.net/asdfghwunai/article/details/88947374