c++ - 在 C++11 中获取函数指针的语法

标签 c++ c++11 pointer-to-member

我正在尝试理解函数指针,并且我有以下测试代码:

#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.

关于c++ - 在 C++11 中获取函数指针的语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47676643/

相关文章:

用于评估数学/算术表达式的 C++ 仿函数库

C++ 模块定义文件头内联符号

c++ - C++ 中的双整数转换

c++ - boost::read_graphml Visual Studio 2013

c++ - 排序比较函数可以是成员函数上的指针吗?

python - 如何使用 CUDA CURAND 保存和恢复随机数生成器的状态?

c++ - 使用基于范围的 for 迭代临时 std::initializer_list

c++ - 如何从具有特化的类模板中定义静态成员变量?

c++ - 指向成员函数的指针和多重继承

c - struct 有一个函数指针,指向一个函数,该函数接受所述结构的指针..需要预定义吗?