为什么相应成员不能正确访问成员函数指针?
Why are member function pointers not accessed properly by corresponding members?
考虑这个代码片段。
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();
}
我有一个 class B。它的私有成员是一个指向 B 的指针,即 m_b 和一个函数指针。
在init()函数中,给出私有成员函数指针up(),私有成员函数指针m_b给出down()
当我 运行 代码时,B::up() 被执行两次,而不是执行 B::up() 然后 B::down()。
发生这种情况是因为您将一个对象的 m_execute
应用到另一个对象。
通过更改此行来解决此问题
(m_b->*m_execute)();
// ^^^^^^^^^
// Points to your m_execute, not m_b's
对此:
(m_b->*m_b->m_execute)();
更好的是,将成员函数添加到 运行 你自己的执行,并从 B::find
:
调用它
void find() {
run_my_execute();
m_b->run_my_execute();
}
void run_my_execute() {
(this->*m_execute)();
}
这将避免混淆谁的指针应该应用于什么对象。
考虑这个代码片段。
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();
}
我有一个 class B。它的私有成员是一个指向 B 的指针,即 m_b 和一个函数指针。 在init()函数中,给出私有成员函数指针up(),私有成员函数指针m_b给出down() 当我 运行 代码时,B::up() 被执行两次,而不是执行 B::up() 然后 B::down()。
发生这种情况是因为您将一个对象的 m_execute
应用到另一个对象。
通过更改此行来解决此问题
(m_b->*m_execute)();
// ^^^^^^^^^
// Points to your m_execute, not m_b's
对此:
(m_b->*m_b->m_execute)();
更好的是,将成员函数添加到 运行 你自己的执行,并从 B::find
:
void find() {
run_my_execute();
m_b->run_my_execute();
}
void run_my_execute() {
(this->*m_execute)();
}
这将避免混淆谁的指针应该应用于什么对象。