作者热门文章
- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
如果我有一个纯虚拟基类及其多个派生...
class Base
{
public:
virtual void method1() = 0;
}
class Derived1 : public Base
{
public:
void method1() override { ... }
}
class Derived2 : public Base
{
public:
void method1() override { ... }
}
有什么方法可以让持有未知派生类型对象的 Base*
的代码确定它持有的对象的 method1()
函数的地址Base*
指针指向?
我想做的是这样的:
void someOtherFunction(Base * pb)
{
printf("If I call pb->method1(), it will call a function at %p.\n",
&(pb->method1));
}
但是我得到一个编译器错误:
error: ISO C++ forbids taking the address of a bound member function to form a pointer to member function.
理想情况下,任何解决方案都应避免 RTTI 和 dynamic_cast
,因为我的嵌入式系统未启用/不允许这样做。
最佳答案
您要找的是pointer to (virtual) member function .请注意,这样的指针不是函数的地址,而通常是 vtable 中的偏移量,因为实际调用的函数取决于对象的实际类型。您甚至不能将此指针转换为 void*
,表示是实现定义的。 这也意味着您无法找到将以通用方式调用的实际函数的地址。
如果您真的需要知道要调用的目标函数,也许使用几个单独的函数和一个枚举会更好?
无论如何,如果你只是想能够通过指针调用虚成员函数,你可以这样做:
void someOtherFunction(Base* pb)
{
using func_t = void(Base::*)(); // Type of a pointer to member function of
// signature void() and object type Base
func_t fn = &Base::method1; // Take the address of the function
(pb->*fn)(); // Call it. Note the extra parenthesis and the operator: ->*
// The actual function called depends on the actual type of pb,
// it can be Derived1::f() or Derived2::f() in the example code you have
}
关于C++ 多态性 : Is there any way to find the address of an object's member function?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51328431/
我是一名优秀的程序员,十分优秀!