Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/140.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++ - Fatal编程技术网

C++ 类中的常量静态函数指针~如何初始化它?

C++ 类中的常量静态函数指针~如何初始化它?,c++,C++,我有一小段代码: int add(int x, int y) { return x + y; } class A { public: const static int (*FP)(int, int) = &add; }; int main() { int x = 3; int y = 2; int z = A::FP(x, y); return 0; } 在VS2012下,这会生成以下错误: 错误C2864:“A::FP”:在类中只能

我有一小段代码:

int add(int x, int y)
{
    return x + y;
}

class A
{
public:
    const static int (*FP)(int, int) = &add;
};

int main()
{
    int x = 3;
    int y = 2;
    int z = A::FP(x, y);
    return 0;
}
在VS2012下,这会生成以下错误: 错误C2864:“A::FP”:在类中只能初始化静态常量整型数据成员

有什么我没看见的吗?还是因为某些原因,这显然是不可能的


Christian

在类定义之外初始化,使用
typedef
使
常量成为可能:

typedef int (*func_t)(int, int);

class A
{
public:
    const static func_t FP;
};

const func_t A::FP = &add;
没有
typedef
声明:

const static int (*FP)(int, int) = &add;
是名为
FP
静态
函数指针,返回类型为
const int
,而不是
const
函数指针。使用警告级别
/W4
编译时,会发出以下诊断信号:

警告C4180:应用于函数类型的限定符没有意义;忽略


由于C++03中声明的顺序为
const static int
,而不是
static const int
,,因此这一点并不明显。不允许类内初始化
非整数
枚举
数据类型

class A
{
public:
    typedef int (*FP_ptr)(int, int);
    const static FP_ptr FP;
};

const A::FP_ptr 
A::FP = &add;

C++11


非常感谢,伙计们。我最近也有同样的问题。只想在正确的位置添加带有“const”的答案,而不声明新类型:

class A
{
public:
    static int (* const FP)(int, int);
};

int (* const A::FP)(int, int) = &add;
可以将最后一行更改为(我不确定是否完全相同,但它可以工作):

另一种方式(其他人如何解决类似问题)是:

class A
{
public:
    static int FP(int, int);
};

int A::FP(int x, int y)
{
    return add( &x, &y );
}

您可以在类构造函数初始化列表中设置它吗?错误消息中没有隐藏的含义。“只有静态常量整型数据成员”的意思正是它所说的。因为函数指针不是整数,所以不能这样做。在类之外的.cpp文件中初始化它们。@n.m感谢您解释整型数据成员是什么。我不是以英语为母语的人,所以有时候发现这些东西是一种冒险。没有typedef,这是正确的吗?
const
属于没有它的返回类型,不是吗?@jrok,是的。由于
const int…
被视为
return
类型,我无法确定在没有
typedef
的情况下使用
const
创建它的方法。当然,在类中的声明中也应该发生同样的事情。所以我想知道为什么gcc抱怨从
const int(*)(int,int)
int(*)(int,int)
@jrok的转换无效,VC编译器警告声明和定义中都有无意义的限定符。也感谢C++11版本!很遗憾Visual Studio还不支持此C++11功能。。。
int (* const A::FP)(int, int) = add;
class A
{
public:
    static int FP(int, int);
};

int A::FP(int x, int y)
{
    return add( &x, &y );
}