我在使用成員函式指標時遇到了一些麻煩。我該如何解決這個問題,為什么這不起作用?問題在里面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;
}
uj5u.com熱心網友回復:
的型別vtable_ptr是void (Base::**)(),的型別base->vtable_ptr[0]是void (Base::*)()。您用于呼叫的語法不正確。
我該如何解決
在您的示例中使用指向成員函式 的指標的正確語法void (Base::*)()如下所示:
(base->*(base->vtable_ptr[0]))();
Derived請注意,您提供的最小可重現示例中不需要該類。
作業演示
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/474878.html
