gpt4 book ai didi

c++ - 调用成员函数指针

转载 作者:行者123 更新时间:2023-12-04 22:17:57 26 4
gpt4 key购买 nike

如何调用分配给成员函数的成员函数指针?我正在学习回调,这只是为了学习目的。如何调用 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;
}

最佳答案

你快到了。回想一下 m_ptr 本身就是一个数据成员,因此为了访问它,您需要告诉编译器解决与持有成员指针的实例的关系。像这样调用它:

 (t.*t.m_ptr)();
// ^^ this was missing

关于c++ - 调用成员函数指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57989027/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com