如何调用分配给成员函数的成员函数指针?我正在学习回调,这只是出于学习目的。如何调用m_ptr函数?
class Test{
public:
void (Test::*m_ptr)(void) = nullptr;
void foo()
{
std::cout << "Hello foo" << std::endl;
}
};
void (Test::*f_ptr)(void) = nullptr;
int main()
{
Test t;
f_ptr = &Test::foo;
(t.*f_ptr)();
t.m_ptr = &Test::foo;
// t.Test::m_ptr(); //Does not work
// t.m_ptr(); //Does not work
// (t.*m_ptr)(); //Does not work
return 0;
}
Run Code Online (Sandbox Code Playgroud)
你快到了 回想一下,m_ptr它本身就是数据成员,因此,要访问它,您需要告诉编译器将其与持有指向该成员的指针的实例的关系解析。这样称呼它:
(t.*t.m_ptr)();
// ^^ this was missing
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
71 次 |
| 最近记录: |