【问题标题】:Visual Studio 'non-standard syntax; use '&' to create a pointer to member' [duplicate]Visual Studio '非标准语法;使用'&'创建指向成员的指针'[重复]
【发布时间】:2017-03-02 14:03:04
【问题描述】:

我试图用函数指针调用一个函数,其中函数指针是类成员。

我简化了代码以仅展示问题,但原始代码中的 foo() 函数已编写,因此我无法更改它。

(在我的实际代码中,foo 来自 GLFW (glfwSetKeyCallback),A 是一个输入处理程序类。)

代码是:

    #include <iostream>

    // this four line can not be changed
    typedef void(*fptr)(int);
    void foo(fptr f) {
        f(0);
    }

    void testOutA(int i) {
    }

    class A {
    public:
        void testInA(int i) {
        }
    };

    int main()
    {
        foo(testOutA); // works fine as it should be

        A * a = new A();

        foo(a->testInA); // ERROR

        return 0;
    }

编译错误信息为:

错误:错误 C3867:'A::testInA':非标准语法;使用 '&' 创建指向成员的指针

【问题讨论】:

  • 错误信息是什么?
  • 您是否尝试使用&amp; 创建指向成员的指针,如错误所示?
  • 好吧,我尝试添加 & 但我不知道在哪里添加它到目前为止我尝试了以下这些,但这些显然是错误的:&a->testInA, a->&testInA, &(a ->testInA)
  • 这样不行。你有什么版本的 C++ 可用?

标签: c++ visual-studio function class pointers


【解决方案1】:

表达式a-&gt;testInA类型是一个指向非static成员函数的指针。

它与fptr 的类型不同,因此编译器会发出一个错误,尽管是一个神秘的错误。

如果testInAstatic,则编译将通过。

更多详情请见C++ function pointer (class member) to non-static member function

【讨论】:

    猜你喜欢
    • 2015-11-10
    • 1970-01-01
    • 2017-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-30
    • 1970-01-01
    相关资源
    最近更新 更多