Pointer to member function syntax

大兔子大兔子 提交于 2019-12-05 23:27:32

Simple syntax subtleties.

func = &TestClass::TestMethod;
//     ^ Missing ampersand to form a pointer-to-member

TestClass tc;
(tc.*func)(10, 20);
// ^^ Using the dot-star operator to dereference the pointer-to-member,
// while minding its awkward precedence with respect to the call operator.

func = TestClass::TestMethod; should be func = &TestClass::TestMethod;, and tc.func(10, 20) should be (tc.*func)(10, 20) (in the latter, note that there are two changes: . becomes .*, and there are added parentheses; both are needed).

Pointers to members (functions or otherwise), are very different than regular pointers, despite having some similarity in the syntax. The way that regular functions act like pointers to functions, and vice-versa, is inherited from C, but C doesn't support pointers to members, so it wasn't necessary for those to work that way in C++.

To make a pointer to member, you have to explicitly use &, and you have to explicitly use .* to indirect it, which is perhaps more what you might expect if you weren't used to the way functions work in C:

func = &TestClass::TestMethod;
(tc.*func)(10, 20);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!