zoukankan      html  css  js  c++  java
  • C++对C语言的拓展(5)—— 函数重载和函数指针结合

    1、函数指针的介绍

    函数指针指向某种特定类型,函数的类型由其参数及返回类型共同决定,与函数名无关。举例如下:

    int add(int nLeft,int nRight);//函数定义  

    该函数类型为int(int,int),要想声明一个指向该类函数的指针,只需用指针替换函数名即可

    int (*pf)(int,int);//未初始化 

    pf可指向int(int,int)类型的函数。pf前面有*,说明pf是指针,右侧是形参列表,表示pf指向的是函数,左侧为int,说明pf指向的函数返回值为int。则pf可指向int(int,int)类型的函数。而add类型为int(int,int),则pf可指向add函数。

    pf = add;//通过赋值使得函数指针指向某具体函数  

    注意:*pf两端的括号必不可少。

    2、函数指针基本语法

    //方法一:
    typedef void (myTypeFunc)(int a, int b);//声明一个函数类型
    myTypeFunc *myfuncp = NULL;//定义一个函数指针,这个指针指向函数的入口地址
    //方法二:
    typedef void (*myPTypeFunc)(int a, int b);//声明一个函数指针类型
    myPTypeFunc fp = NULL;//通过函数指针类型定义了一个函数指针
    //方法三:
    void (*myVarPFunc)(int a,int b);//定义一个函数指针变量

    当时用重载函数名对函数指针进行赋值时,根据重载规则挑选与函数指针参数列表一致的候选者,严格匹配候选者的函数类型指针的函数类型。

    #include <iostream>
    using namespace std;
    
    int func(int x)
    {
        return x;
    }
    
    int func(int a, int b)
    {
        return a+b;
    }
    
    int func(const char* s)
    {
        return strlen(s);
    }
    
    typedef int(*pf1)(int a);//int(*)(int a)
    typedef int(*pf2)(int a,int b);//int(*)(int a,int b)
    
    int main(void)
    {
        int c = 0;
    
        pf1 p1 = func;
        c = p1(1);
        printf("c=%d
    ", c);
    
        pf2 p2 = func;
        c = p2(1,2);
        printf("c=%d
    ", c);
    
        retu

     3、函数重载总结

    • 重载函数在本质上是相互独立的不同函数。
    • 函数的函数类型是不同的;
    • 函数返回值不能作为函数重载的依据;
    • 函数重载是由函数名参数列表决定的。
  • 相关阅读:
    web api 特点
    码农
    到程序员短缺的地方生活,不要到过剩的地方凑热闹
    程序员也要寻找贸易的机会,要参加研讨会
    [Codeforces 863D]Yet Another Array Queries Problem
    [Codeforces 863C]1-2-3
    [Codeforces 864F]Cities Excursions
    [Codeforces 864E]Fire
    [Codeforces 864D]Make a Permutation!
    [Codeforces 864C]Bus
  • 原文地址:https://www.cnblogs.com/yuehouse/p/9787126.html
Copyright © 2011-2022 走看看