之前一直没总结过的知识点,很重要的知识,实际工作中也经常遇到。
如题:2019年10月

分析:
还是太想当然了,但凡想想c的函数指针,或想想内存中的表示,也不会出错。也说明,对这一知识点并不牢靠。
解决
这里的成员函数,并没有说是不是静态的还是一般的成员函数,静态的成员函数,是可以不带&的,所以答案B,不能说没有道理~若是一般的成员函数,则一定要带&。
后记
写到这里的时候,自考已经结束两天了,也就是说这篇由于时间原因,在自考前没有写,但觉得这块确实挺常用,所以在自考完后再补充上。以后的学习,就不再上传复习的内容了,只上传些会工作中会使用到的考点。每次考完都有不同的感受,同时也会做一些学习上的调整。
扩展:
想到的第一个问题的,还是指针函数与函数指针的区别
之前其实,看过从别的书,尤其是c的书,看过很多遍了,但想想,还是不太清晰或者,根本就没什么印象了。
函数指针,是一个指针。指向一个函数的指针
指针函数,是指的函数的返回值是一个指针。
指针函数
定义:类型标识符 *函数名(参数表) ;//函数名前不带()
使用:
int *f(int a, int b); // 声明指针函数
#include <stdio.h>
#include<stdlib.h>
int main(int argc, char *argv[])
{
printf("------------------------------ Start\n");
int *p1 = NULL;
printf("The memeory address of p1 = 0x%x \n", p1);
p1 = f(10, 24);
printf("The memeory address of p1 = 0x%x \n", p1);
printf("*p1 = %d \n", *p1);
printf("------------------------------ End\n");
getchar();
return 0;
}
/*指针函数的定义,返回值是指针类型int */
int *f(int a, int b)
{
int *p = (int *)malloc(sizeof(int));
printf("The memeory address of p = 0x%x \n", p);
memset(p, 0, sizeof(int));
*p = a + b;
printf("*p = %d \n", *p);
return p;
}
c函数指针
真正有用的部分!!
定义格式:类型说明符 (*函数名)(参数);//此处的函数名变成了一个指针(实际就是指针变量)
使用:
#include<stdio.h>
#include<stdlib.h>
int max(int a, int b)
{
return a > b ? a : b;
}
int min(int a, int b)
{
return a < b ? a : b;
}
int(*f)(int, int); // 声明函数指针,指向返回值类型为int,有两个参数类型都是int的函数
int main()
{
printf("------------------------------ Start\n");
f = max; //函数指针赋值书写形式
int c = (*f)(15, 19);//函数指针的调用形式
printf("The max value is %d \n", c);
f = min; // 函数指针f指向求最小值的函数min(将min函数的首地址赋给指针f)
c = (*f)(12, 65);
printf("The min value is %d \n", c);
printf("------------------------------ End\n");
getchar();
return 0;
}
c++函数指针
定义形式:返回类型 (类名称::*函数成员名称)(参数类型,参数类型,参数类型,….);
使用:
#include <iostream>
using namespace std;
class test
{
public:
test()
{
cout<<"constructor"<<endl;
}
int fun1(int a, char c)
{
cout<<"this is fun1 call:"<<a<<" "<<c<<endl;
return a;
}
void fun2(double d)const
{
cout<<"this is fun2 call:"<<d<<endl;
}
static double fun3(char buf[])
{
cout<<"this is fun3 call:"<<buf<<endl;
return 3.14;
}
};
int main()
{
// 类的静态成员函数指针和c的指针的用法相同
double (*pstatic)(char buf[]) = NULL;//不需要加类名
pstatic = test::fun3; //可以不加取地址符号
pstatic("myclaa");
pstatic = &test::fun3;
(*pstatic)("xyz");
//普通成员函数
int (test::*pfun)(int, char) = NULL; //一定要加类名
pfun = &test::fun1; //一定要加取地址符号
test mytest;
(mytest.*pfun)(1, 'a'); //调用是一定要加类的对象名和*符号
//const 函数(基本普通成员函数相同)
void (test::*pconst)(double)const = NULL; //一定要加const
pconst = &test::fun2;
test mytest2;
(mytest2.*pconst)(3.33);
// //构造函数或者析构函数的指针,貌似不可以,不知道c++标准有没有规定不能有指向这两者的函数指针
// (test::*pcon)() = NULL;
// pcon = &test.test;
// test mytest3;
// (mytest3.*pcon)();
return 0;
}
c++标准有没有规定不能有指向这两者的函数指针
// (test::*pcon)() = NULL;
// pcon = &test.test;
// test mytest3;
// (mytest3.*pcon)();
return 0;
}
本文详细解析了C/C++中函数指针的概念,包括指针函数与一般函数指针的差异,通过实例演示了如何定义和使用它们,以及在C++中针对类成员函数指针的特殊处理。重点强调了实际工作中的应用场景和常见误区。
2887

被折叠的 条评论
为什么被折叠?



