在 C++11 中获取函数指针的语法
Syntax to get function pointers in C++11
我正在尝试理解函数指针,我有以下测试代码:
#include <iostream>
using namespace std;
class Test {
public:
void test_func() {
cout << "Test func called.";
}
};
void outer_test_func(Test &t, void (Test::*func)()) {
(t.*func)();
}
int main(int argc, char *argv[]) {
auto t = Test();
outer_test_func(t, &Test::test_func);
}
这行得通。但据我了解 Test::test_func
和 &Test::test_func
都会产生指针。那么为什么我不能使用前者而不是后者呢?如果我尝试它,g++ 会抱怨。
But from what I understand Test::test_func and &Test::test_func both result in pointers.
Test::test_func
不是创建成员函数指针或数据成员指针的有效语法。它从来都不是有效的 C++ 语法。
来自 cppreference(强调我的),
A pointer to non-static member object m which is a member of class C can be initialized with the expression &C::m exactly. Expressions such as &(C::m) or &m inside C's member function do not form pointers to members.
我正在尝试理解函数指针,我有以下测试代码:
#include <iostream>
using namespace std;
class Test {
public:
void test_func() {
cout << "Test func called.";
}
};
void outer_test_func(Test &t, void (Test::*func)()) {
(t.*func)();
}
int main(int argc, char *argv[]) {
auto t = Test();
outer_test_func(t, &Test::test_func);
}
这行得通。但据我了解 Test::test_func
和 &Test::test_func
都会产生指针。那么为什么我不能使用前者而不是后者呢?如果我尝试它,g++ 会抱怨。
But from what I understand Test::test_func and &Test::test_func both result in pointers.
Test::test_func
不是创建成员函数指针或数据成员指针的有效语法。它从来都不是有效的 C++ 语法。
来自 cppreference(强调我的),
A pointer to non-static member object m which is a member of class C can be initialized with the expression &C::m exactly. Expressions such as &(C::m) or &m inside C's member function do not form pointers to members.