zoukankan      html  css  js  c++  java
  • C++函数指针

    为了复试,重新从零翻开了一遍C++程序设计基础,看到函数指针,才想到这个地方我一开始学的时候就没学懂,趁这次机会把它搞懂。直接上代码,注释很详细:

    #include <iostream>
    using namespace std;
    
    typedef int (*funType)(int, int);
    typedef int funType2(int, int);
    
    typedef int *(*pfunType)(int, int);
    typedef int *(pfunType2)(int, int);
    
    int funA(int a, int b)
    {
    	cout << "调用了 int funA()" << endl;
    	return a + b;
    }
    
    int *funB(int a, int b)
    {
    	cout << "调用了int *funB()" << endl;
    	int *p = new int;
    	*p = a - b;
    	return p;
    }
    
    
    void callFunA(funType* cfun, int a, int b)//这里传递的是funType类型的指针
    {
    	cout << (*cfun)(a, b) << endl;// ok,这里是解指针调用
    	//cout << cfun(a, b) << endl; //error 明显调用表达式前的括号必须具有(指针)函数类型
    }
    
    void callFunA2(funType cfun, int a, int b)//这里传递的是funType类型变量
    {
    	cout << (*cfun)(a, b) << endl;//ok,这里是解指针调用
    	cout << cfun(a, b) << endl;//ok,这里直接调用
    }
    
    void callFunB(pfunType* pcfun, int a, int b)
    {
    	int *p = (*pcfun)(a, b);
    	//int *p = pcfun(a, b);//error 明显调用表达式前的括号必须具有(指针)函数类型
    	cout << *p<< endl;
    	delete p;
    }
    
    void callFunB2(pfunType2 pcfun, int a, int b)
    {
    	int *p1 = (*pcfun)(a, b);//ok
    	int *p2 = pcfun(a, b);//ok
    
    	cout << *p1 << endl;
    	cout << *p2 << endl;
    
    	delete p1;
    	delete p2;
    }
    
    int main()
    {
    	int a = 5, b = 8;
    
    	funType fT = funA; //ok
    	//funType* fT_p = &funA;//error 类型参数不兼容
    	//funType2 fT2 = funA;//error 未能初始化fT2,怎么能初始化fT2?,难道funType2 就不能用来声明函数对象?
    
    	pfunType pfT = funB;//0k
    	//pfunType2 pfT2 = funB;//error 同fT2
    
    	callFunA(&fT, a, b);//0k
    	//callFunA(funA, a, b);//error 类型参数不兼容,尝试直接传递funA函数入口地址失败
    	callFunA2(fT, a, b);//ok
    	
    	callFunB(&pfT, a, b);//ok
    	//callFunB(funB, a, b);//error 类型参数不兼容
    	callFunB2(pfT, a, b);//ok
    	callFunB2(funB, a, b);//ok
    
    
    	system("pause");
    	return 0;
    }

  • 相关阅读:
    Ocelot简易教程(二)之快速开始1
    Ocelot简易教程(一)之Ocelot是什么
    InfluxDB学习之InfluxDB的基本操作
    InfluxDB入门教程
    .NET Core微服务之基于App.Metrics+InfluxDB+Grafana实现统一性能监控
    .net Core 微服务
    IdentityServer4 接口说明
    WINDOWS命令行关闭本地占用的端口
    并发负载压力测试
    C#操作Mongodb
  • 原文地址:https://www.cnblogs.com/wangzhizhen/p/10545731.html
Copyright © 2011-2022 走看看