指向成员函数语法的指针 [英] Pointer to member function syntax
问题描述
我试图把头放在成员函数的指针周围,并被这个示例所困扰:
I'm trying to wrap my head around pointers to member functions and am stuck with this example:
#include <iostream>
class TestClass {
public:
void TestMethod(int, int) const;
};
void TestClass::TestMethod(int x, int y) const {
std::cout << x << " + " << y << " = " << x + y << std::endl;
}
int main() {
void (TestClass::*func)(int, int) const;
func = TestClass::TestMethod;
TestClass tc;
tc.func(10, 20);
return 0;
}
我认为代码应该做什么:
What I think the code should do:
- 在main的第一行中,我声明一个指向
class TestClass
成员函数的指针,该成员函数不返回任何内容/采用两个int
并被声明为const
,称为 func . - 第二行将成员函数
TestMethod
(属于类TestClass
)分配给func
,这满足这些条件. - 第四行创建一个名为 tc 的
TestClass
对象. - 第五行尝试在
TestClass
-对象tc
上调用func
指向的成员函数.
- In the first line of main I declare a pointer to a member function of
class TestClass
, which returns nothing/takes twoint
's and is declaredconst
, called func. - The second line assigns the member-function
TestMethod
(of classTestClass
) tofunc
, which satisfies these criteria. - The forth line creates an
TestClass
-object called tc. - The fifth line tries to call the member function pointed to by
func
on theTestClass
-objecttc
.
我遇到两个编译错误:
-
而不是将
TestClass::TestMethod
分配给func
.编译器尝试调用TestClass::TestMethod
(即使不是static
,因此也会引发错误):
Instead of assigning
TestClass::TestMethod
tofunc
. The compiler tries to callTestClass::TestMethod
(even though it's notstatic
, therefore throws an error):
testPointerToMemberFunc.cpp:14:21: error: call to non-static member function without an object argument
func = TestClass::TestMethod;
~~~~~~~~~~~^~~~~~~~~~
编译器尝试在tc
上调用名为func
的函数,而不是调用func
指向的函数.在我看来,好像func
的声明方式不正确(作为指向成员函数的指针):
The compiler tries to call a function named func
on tc
, instead of the function, pointed to by func
. To me this seems, like func
isn't declared the right way (as a pointer to a member function):
testPointerToMemberFunc.cpp:17:6: error: no member named 'func' in 'TestClass'
tc.func(10, 20);
~~ ^
我在做什么错了?
推荐答案
简单的语法细节.
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.
这篇关于指向成员函数语法的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!