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 );
}