访问指向成员函数的指针数组的元素
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::*)()
。您用于调用的语法不正确。
How do I fix this
在您的示例中使用 成员函数指针 void (Base::*)()
的正确语法如下所示:
(base->*(base->vtable_ptr[0]))();
请注意,在您提供的最小可重现示例中不需要 Derived
class。
我在使用成员函数指针时遇到了一些问题。我该如何解决这个问题,为什么它不起作用?问题出在 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::*)()
。您用于调用的语法不正确。
How do I fix this
在您的示例中使用 成员函数指针 void (Base::*)()
的正确语法如下所示:
(base->*(base->vtable_ptr[0]))();
请注意,在您提供的最小可重现示例中不需要 Derived
class。