函数指向类成员的指针

编程入门 行业动态 更新时间:2024-10-24 14:18:13
本文介绍了函数指向类成员的指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想这样做:

class A { void *(*func)(void *); A(void *(*function)(void *)){ func = function; } } class B { void *real_func(void *); A ptr; B() :ptr(&real_func) { ... } }

但我收到此错误:

错误:ISO C ++禁止使用非限定或括号非静态成员函数的地址形成指向成员函数的指针。

error: ISO C++ forbids taking the address of an unqualified or parenthesized non-static member function to form a pointer to member function.

有人知道如何初始化函数指向同一类中的函数成员

Someone knows how to initialize the function pointer to a function member in the same class???

谢谢!

Carlos

推荐答案

由于 real_func 成员函数,其类型不能为 void *(*)()。相反,它是 void *(B :: *)()所以你需要相应地声明 func p>

Since real_func is not a static member function, its type cannot be void *(*)(). Instead, it is void *(B::*)() so you need to declare func accordingly:

void *(B::*func)(); // call it like this pointer_to_b->*func();

如果你很小心,你也可以使用指针A作为基类,确保指向A的指针指向B的实例:

If you are careful, you can also use pointer to A as the base class, but you must make sure that the pointer to A points to an instance of B:

void *(A::*func)();

但是,现在大多数情况下只是复制虚拟成员函数的功能。所以我建议你改用:

At this point, however, you are mostly just replicating the functionality of virtual member functions. So I would recommend you use that instead:

class A { virtual void *func() = 0; }; class B { void *func() { // ... } };

更多推荐

函数指向类成员的指针

本文发布于:2023-07-28 02:42:01,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1226549.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:指针   函数   成员

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!