[英]Accessing element of array of pointers to member functions
我在使用成员函数指针时遇到了一些麻烦。 我该如何解决这个问题,为什么这不起作用? 问题在main()
内部……或者我猜!
#include <iostream>
#include <functional>
template<typename T>
using FnctPtr = void(T::*)(); // pointer to member function returning void
class Base {
public:
Base() : vtable_ptr{ &virtual_table[0] } {}
void foo() {
std::cout << "Base";
}
void x() {
std::cout << "X";
}
private:
// array of pointer to member function returning void
inline static FnctPtr<Base> virtual_table[2] = { &Base::foo, &Base::x };
public:
FnctPtr<Base>* vtable_ptr;
};
class Derived : public Base {
public:
Derived() {
vtable_ptr = reinterpret_cast<FnctPtr<Base>*>(&virtual_table[0]);
}
void foo() /* override */ {
std::cout << "Derived";
}
public:
inline static FnctPtr<Derived> virtual_table[2] = { &Derived::foo, &Base::x };
};
int main() {
Base* base = new Base();
base->vtable_ptr[0](); // Issue here
delete base;
}
vtable_ptr
的类型是void (Base::**)()
而base->vtable_ptr[0]
的类型是void (Base::*)()
。 您用于调用的语法不正确。
我该如何解决
在您的示例中使用指向成员函数void (Base::*)()
的指针的正确语法如下所示:
(base->*(base->vtable_ptr[0]))();
请注意,您提供的最小可重现示例中不需要Derived
类。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.