指向成员函数语法的指针
Pointer to member function syntax
我正试图把我的头绕在成员函数的指针上,我被这个例子困住了:
#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;
}
我认为代码应该做什么:
- 在main的第一行,我声明了一个指向
- 第二行将
TestClass
类的成员函数TestMethod
赋值给func
,满足这些条件。 第四行创建了一个 - 第五行试图调用
TestClass
-objecttc
上func
所指向的成员函数。
class TestClass
成员函数的指针,该函数不返回任何值/接受两个int
,并声明为const
,称为func。TestClass
对象,名为tc。我得到两个编译错误:
代替将
TestClass::TestMethod
分配给func
。编译器尝试调用TestClass::TestMethod
(即使它不是static
,因此抛出错误):testPointerToMemberFunc.cpp:14:21: error: call to non-static member function without an object argument func = TestClass::TestMethod; ~~~~~~~~~~~^~~~~~~~~~
编译器尝试在
tc
上调用名为func
的函数,而不是func
所指向的函数。在我看来,就像func
没有以正确的方式声明(作为指向成员函数的指针):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.
func = TestClass::TestMethod;
应该是func = &TestClass::TestMethod;
, tc.func(10, 20)
应该是(tc.*func)(10, 20)
(在后者中,注意有两个变化:.
变成了.*
,并且增加了括号;
指向成员(函数或其他)的指针与常规指针非常不同,尽管在语法上有一些相似之处。常规函数的行为方式类似于指向函数的指针,反之亦然,都是从C继承来的,但C不支持指向成员的指针,因此在c++中没有必要这样做。
要创建一个指向成员的指针,必须显式地使用&
,并且必须显式地使用.*
来间接它,如果您不习惯C中函数的工作方式,这可能更符合您的期望:
func = &TestClass::TestMethod;
(tc.*func)(10, 20);