卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章78967本站已运行4411

C++ 函数指针:通用函数指针

是的,c++++ 中存在通用函数指针。具体步骤如下:声明通用函数指针:void* genericfuncptr;将函数强制转换为 void 类型的指针:genericfuncptr = reinterpret_cast(&myfunc);使用强制转换将其转换为函数指针类型:int (*calledfunc)(int) = reinterpret_cast(&genericfuncptr);使用函数指针调用函数:calledfunc(5);

C++ 函数指针:通用函数指针

C++ 函数指针:使用通用函数指针

简介

函数指针是一种强大的 C++ 特性,它允许您将函数作为普通数据来处理。通用函数指针是一种特殊的函数指针,可以指向具有任何签名(即参数和返回值类型)的函数。

立即学习“C++免费学习笔记(深入)”;

声明通用函数指针

要声明一个通用函数指针,请使用 void* 数据类型:

void* genericFuncPtr;

将函数赋值给通用函数指针

要将函数赋值给通用函数指针,请将函数强制转换为 void*:

genericFuncPtr = reinterpret_cast<void*>(myFunc);

在这里,myFunc 是要分配的函数。

从通用函数指针调用函数

要从通用函数指针调用函数,请使用强制转换将其转换为函数指针类型:

int (*calledFunc)(int) = reinterpret_cast<int (*)(int)>(genericFuncPtr);
int result = calledFunc(5);

在这里,calledFunc 是使用通用函数指针创建的函数指针,它指向与 myFunc 相同的函数。

实例

以下是一个使用通用函数指针的示例:

#include <iostream>
#include <functional>

using namespace std;

void print_value(int value) {
    cout << "Value: " << value << endl;
}

void print_string(string str) {
    cout << "String: " << str << endl;
}

int main() {
    // 创建通用函数指针
    void* genericFuncPtr;

    // 分配要调用的函数
    genericFuncPtr = reinterpret_cast<void*>(print_value);

    // 使用强制转换为函数指针类型
    int (*funcPtr)(int) = reinterpret_cast<int (*)(int)>(genericFuncPtr);

    // 使用函数指针调用函数
    funcPtr(5);

    // 再次分配通用函数指针,指向另一个函数
    genericFuncPtr = reinterpret_cast<void*>(print_string);

    // 更新函数指针类型
    funcPtr = reinterpret_cast<void (*)(string)>(genericFuncPtr);

    // 调用函数
    funcPtr("Hello, world!");

    return 0;
}

输出:

Value: 5
String: Hello, world!
卓越飞翔博客
上一篇: C++ 函数指针:在多线程环境下的应用
下一篇: 返回列表
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏