Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/129.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++ Visual Studio 2015不允许我初始化函数指针_C++_Function Pointers - Fatal编程技术网

C++ Visual Studio 2015不允许我初始化函数指针

C++ Visual Studio 2015不允许我初始化函数指针,c++,function-pointers,C++,Function Pointers,我正在尝试创建一个函数指针。我的代码: 头文件: #pragma once #include <stdio.h> class my_class { private: int function(int x); int *(*foo)(int); public: my_class(); ~my_class(); }; 但是my_类::my_类中的行给出了以下错误: error C2276: '&': illegal operation on

我正在尝试创建一个函数指针。我的代码:

头文件:

#pragma once
#include <stdio.h>

class my_class
{
private:
    int function(int x);
    int *(*foo)(int);

public:
    my_class();
    ~my_class();
};
但是my_类::my_类中的行给出了以下错误:

error C2276: '&': illegal operation on bound member function expression
将鼠标光标放在所述行中的=上会显示以下工具提示:

a value of type "int (my_class::*)(int x)" cannot be assigned to an entity of type "int *(*)int"

如何使其工作?

您认为编译器将为您执行隐式类型转换,从指向成员函数的指针转换为指向普通函数的指针。但事实并非如此

通常不使用指向成员函数的指针,因为对象的实例被分配了一定数量的内存,因此指向成员函数的指针可能不完全指向该函数,并可能导致错误的结果

您可以通过两种方式修复它:

将成员函数定义为静态函数。静态成员函数不附加到任何特定对象,可以在没有范围解析操作符的情况下使用。 另一种可能的修复方法是使用this指针创建指向成员函数的指针。
函数类型&my_类::函数为int my_类::*int,而foo需要int**int.int**fooint;没有隐藏此参数,因此无法接受成员函数。关于这一点以及如何修复它的大量信息:函数不仅仅是一个函数;这是一个成员函数。它们的类型不是同义词,因此您的赋值被视为无效。错误消息大大放大了这一点。将函数移出my_类,或将foo更改为指向正确的类型,并准备学习如何通过成员函数指针和this调用成员函数。您必须修复foo的类型或将函数更改为静态并更改返回类型。包括。。。。为什么?被否决是因为这个答案谈到了问题,但没有以一种可能有助于提问者的方式解决问题。@user4581301:我在答案中陈述了一些可能解决提问者问题的修复方法。我是新来的,不知道如何回复帖子。任何进一步的澄清都会非常有帮助
a value of type "int (my_class::*)(int x)" cannot be assigned to an entity of type "int *(*)int"