C++编程基础二 14-函数指针

 1 // C++函数和类 14-函数指针.cpp: 定义控制台应用程序的入口点。
 2 //
 3 
 4 #include "stdafx.h"
 5 #include <iostream>
 6 #include <limits>
 7 #include <string>
 8 #include <array>
 9 #include <math.h>
10 using namespace std;
11 
12 //与数据项类似,函数也有地址。函数的地址是储存其机器语言代码内存的开始地址。
13 //可以将地址作为函数的参数,从而使第一个函数能够找到第二个函数,并运行它。
14 //函数指针指向的是函数而非对象。
15 //想要声明一个可以指向函数的指针,只需要用指针替换函数名即可。
16 //bool(*pf)(const string &, const string &);
17 //pf是一个指向函数的指针,其中该函数的参数是两个const string的引用,返回值是布尔类型。
18 //注意;*pf两端的括号必不可少,如果省略括号,就变成了一个返回值为bool指针的函数,而不是指向函数的指针。
19 //当我们把函数名作为一个值使用时,该函数自动地装换成指针。还可以指向函数的指针调用改函数。
20 
21 
22 bool lengthCompare(const string &s1, const string &s2);
23 void display(const string &s1, const string &s2, bool(*p)(const string &, const string &));
24 int main()
25 {
26     string name1 = "lebin";
27     string name2 = "uimodel";
28     bool res;
29     
30     //bool res = lengthCompare(name1, name2); //直接调用函数
31 
32     bool(*pf)(const string &, const string &); //定义一个函数指针 
33     pf = lengthCompare;                           //给函数指针赋值(pf是指向函数lengthCompare的指针)
34 
35     /*res = pf(name1, name2);        //定义的函数指针pf调用
36     if (res == true)
37     {
38         cout << name1 << "的长度大于" << name2 << endl;
39     }
40     else
41     {
42         cout << name1 << "的长度小于" << name2 << endl;
43     }*/
44 
45     //将pf作为实参传递给display
46     display(name1, name2, pf);
47     return 0;
48 }
49 
50 //对比两个字符串的长度
51 bool lengthCompare(const string &s1, const string &s2)
52 {
53     return size(s1) > size(s2) ? true : false;
54 }
55 
56 //将函数指针作为参数传递给另一个函数,可以直接在这个函数中通过函数指针调用函数指针指向的函数。
57 void display(const string &s1, const string &s2, bool(*p)(const string &, const string &))
58 {
59     if (p(s1, s2) == true) //使用了传递进来的函数指针调用了lengthCompare函数
60     {
61         cout << s1 << "的长度大于" << s2 << endl;
62     }
63     else
64     {
65         cout << s1 << "的长度小于" << s2 << endl;
66     }
67 }

猜你喜欢

转载自www.cnblogs.com/uimodel/p/9348613.html