为什么相应成员不能正确访问成员函数指针

Why are member function pointers not accessed properly by corresponding members?

本文关键字:成员 访问 函数 指针 不能 为什么      更新时间:2023-10-16

考虑一下这个代码片段。

class B {
public:
void up() {
std::cout << "up" << std::endl;
}
void down() {
std::cout << "down" << std::endl;
}
void init( void(B::*someFunc)() , void(B::*otherFunc)() ) {
m_execute = someFunc;
B* newB = new B();
m_b = newB;
m_b->m_execute = otherFunc;
}
void find() {
(this->*m_execute)();
(m_b->*m_execute)();
}
private:
void(B::*m_execute)();
B* m_b;
};
int main(){
B* b = new B();
b->init(&B::up,&B::down);
b->find();
}

我有一个类B。它的私有成员是指向B的指针,即m_B和函数指针。在init((函数中,私有成员函数指针为up((,私有成员m_b的函数指针为down((当我运行代码时,B::up((被执行两次,而不是执行B::up((然后执行B:((。

这是因为您将一个对象的m_execute应用于另一个对象。

通过更改此行来解决此问题

(m_b->*m_execute)();
//     ^^^^^^^^^
// Points to your m_execute, not m_b's

到此:

(m_b->*m_b->m_execute)();

更好的是,添加一个成员函数来运行您自己的execute,并从B::find:调用它

void find() {
run_my_execute();
m_b->run_my_execute();
}
void run_my_execute() {
(this->*m_execute)();
}

这将避免混淆谁的指针应该应用于什么对象。

演示。