Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/webpack/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 无法转换为类型为的函数指针_C++_Function Pointers_Member Function Pointers - Fatal编程技术网

C++ 无法转换为类型为的函数指针

C++ 无法转换为类型为的函数指针,c++,function-pointers,member-function-pointers,C++,Function Pointers,Member Function Pointers,我基本上是试图将一个函数指针分配给我创建的typedef的实例。关于这件事,我有一些阅读材料要读,但我想不出来 标题: #ifndef FUNCPTRTEST_H #define FUNCPTRTEST_H class FuncPtrTest { public: struct position { int x; int y; } ; typedef bool (*CanMove) (position old_pos, position new_

我基本上是试图将一个函数指针分配给我创建的typedef的实例。关于这件事,我有一些阅读材料要读,但我想不出来

标题:

#ifndef FUNCPTRTEST_H
#define FUNCPTRTEST_H

class FuncPtrTest
{
public:
    struct position {
      int x;
      int y;
    } ;

    typedef bool (*CanMove) (position old_pos, position new_pos);
private:
    FuncPtrTest();
    bool FuncExample(position old_pos, position new_pos);
};

#endif // FUNCPTRTEST_H
资料来源:

#include "funcptrtest.h"

FuncPtrTest::FuncPtrTest()
{
    CanMove a = &FuncPtrTest::FuncExample;
}

bool  FuncPtrTest::FuncExample(position old_pos, position new_pos)
{
    return true;
}
错误:

cannot convert 'bool (FuncPtrTest::*)(FuncPtrTest::position, FuncPtrTest::position)' to 'FuncPtrTest::CanMove {aka bool (*)(FuncPtrTest::position, FuncPtrTest::position)}' in initialization
     CanMove a = &FuncPtrTest::CanMove;
不能从非静态成员函数初始化它:

    static bool FuncExample(position old_pos, position new_pos);
 // ^^^^^^

正如消息所说,您试图将成员函数的地址分配给常规函数指针,而不是成员函数指针

获取静态或非成员函数的地址;或将类型更改为成员函数指针

typedef bool (FuncPtrTest::*CanMove) (position old_pos, position new_pos);
例如,在后一种情况下,您需要一个对象来调用它

(this->*a)(old_pos, new_pos);

您正在声明普通函数指针,并试图为其分配成员函数指针。非成员函数指针与成员函数指针不同。原因是成员函数需要一个隐藏的第一个参数,它成为成员函数内的
this
指针。虽然这个隐藏的第一个参数对您是隐藏的,但在某种程度上,它仍然是成员函数签名的一部分。
(this->*a)(old_pos, new_pos);