0
点赞
收藏
分享

微信扫一扫

C/C++ 函数指针(指向函数的指针)高级篇

登高且赋 2022-01-06 阅读 114

代码

头文件:

//
// Created by hsj on 2022/1/6.
//

#ifndef CLION_CPP_T_POINTER_TO_FUNC_H
#define CLION_CPP_T_POINTER_TO_FUNC_H
//函数指针(指向函数的指针测试)高级篇
void test_pointer_to_func();
//一些函数原型
const double * f1(const double arr[],int n);
const double * f2(const double [],int n);
const double * f3(const double *,int n);
#endif //CLION_CPP_T_POINTER_TO_FUNC_H

cpp文件:

//
// Created by hsj on 2022/1/6.
//
#include <iostream>
#include "t_pointer_to_func.h"

//函数指针(指向函数的指针测试)高级篇
void test_pointer_to_func(){

    using namespace std;
    double av[3]{1112.3,1542.6,2227.9};

    //简单的函数指针
    const double * (*p1)(const double arr[],int n) = f1;
    auto p2 = f2;
    cout<<"return addr:"<<(*p1)(av,3)<<"return addr to value:"<<*(*p1)(av,3)<<endl;//风格1
    cout<<"return addr:"<<p2(av,3)<<"return addr to value:"<<*p2(av,3)<<endl;//风格2

    //arrays of pointer(指针数组:数组里面全是指针)
    const double * (*pa[3])(const double arr[],int n) = {f1,f2,f3};
    for (int i = 0; i < 3; ++i) {
        cout<<"[arrays of pointer]return addr:"<<(*pa[i])(av,3)<<"[arrays of pointer]return addr to value:"<<*(*pa[i])(av,3)<<endl;//风格1
        cout<<"[arrays of pointer]return addr:"<<pa[i](av,3)<<"[arrays of pointer]return addr to value:"<<*pa[i](av,3)<<endl;//风格2
    }

    //二级指针(指向指针的指针)
    const double * (**pb)(const double arr[],int n) = pa;
    for (int i = 0; i < 3; ++i) {
        cout<<"[arrays of pointer 2 level]return addr:"<<(*pb[i])(av,3)<<"[arrays of pointer 2 level]return addr to value:"<<*(*pb[i])(av,3)<<endl;//风格1
        cout<<"[arrays of pointer 2 level]return addr:"<<pb[i](av,3)<<"[arrays of pointer 2 level]return addr to value:"<<*pb[i](av,3)<<endl;//风格2
    }

    //指向整个指针数组的指针
    const double * (*(*pc)[3])(const double arr[],int n) = &pa;
    for (int i = 0; i < 3; ++i) {
        cout<<"[arrays of pointer ,pointer arrays of pointer's pointer]return addr:"<<(*(*pc)[i])(av,3)<<"[arrays of pointer ,pointer arrays of pointer's pointer]return addr to value:"<<*(*(*pc)[i])(av,3)<<endl;//风格1
        cout<<"[arrays of pointer ,pointer arrays of pointer's pointer]return addr:"<<((*pc)[i])(av,3)<<"[arrays of pointer ,pointer arrays of pointer's pointer]return addr to value:"<<*((*pc)[i])(av,3)<<endl;//风格2
    }

}
const double * f1(const double arr[],int n){
    return arr;
}
const double * f2(const double arr[],int n){
    return arr + 1;
}
const double * f3(const double *arr,int n){
    return arr + 2;
}

输出:
在这里插入图片描述

举报

相关推荐

函数指针——c++

指向函数的指针

0 条评论