初始化类的静态常量非整数数据成员
考虑下面的示例程序:
#include <iostream>
using namespace std;
class test
{
public:
static const float data;
};
float const test::data = 10; // Line1
int main()
{
cout << test::data;
cout << "\n";
return 0;
}
请注意示例代码中的注释 Line1
。
问题:
Line1
是否正在执行日期成员data
的初始化?- Line1 是初始化静态常量非整数数据成员的唯一方法吗?
Consider the sample program below:
#include <iostream>
using namespace std;
class test
{
public:
static const float data;
};
float const test::data = 10; // Line1
int main()
{
cout << test::data;
cout << "\n";
return 0;
}
Please note the comment Line1
in the sample code.
Questions:
- Is
Line1
doing the initialization of the date memberdata
? - Is
Line1
the only way to initialize a static const non-integral data member?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
当然是这样,并且提供了对象的定义。请注意,这只能在单个翻译单元中完成,因此如果类定义位于头文件中,那么它应该位于源文件中。
在 C++03 中确实如此。在 C++11 中,const 文字类型的任何静态成员都可以在类定义中具有初始化程序。如果该成员是“odr-used”(粗略地说,如果您执行任何需要其地址而不仅仅是其值的操作),您仍然需要该成员的定义。在这种情况下,定义再次需要位于单个翻译单元中,并且不得具有初始值设定项(因为类定义中已经有一个初始值设定项)。
It certainly is, as well as providing the definition of the object. Note that this can only be done in a single translation unit, so if the class definition is in a header file, then this should be in a source file.
In C++03 it was. In C++11, any static member of
const
literal type can have an initialiser in the class definition. You still need a definition of the member if it's "odr-used" (roughly speaking, if you do anything that needs its address, not just its value). In this case, the definition again needs to be in a single translation unit, and must not have an initialiser (since there's already one in the class definition).在现代 C++ 中,您可以内联初始化任何常量表达式。这需要更改语法:
In contemporary C++ you can initialize any constant expression inline. This requires a change of syntax:
data
,其中包括设置其值。编辑:正如 Mike Seymor 指出的那样,#2 已经过时了。根据新的 C++11 标准,1998 年和 C++03 标准仅为整型类型保留的替代语法已扩展到所有常量,无论其类型如何。
data
, which includes setting its value.EDIT: As Mike Seymor pointed out, the #2 is out of date. According to the new C++11 standard, the alternative syntax that was reserved only for integral types by the 1998 and C++03 standards has been extended to all constants, regardless of their type.
2.
在C++11中,你可以说
在C++03中,是的。
2.
In C++11, you can say
In C++03, it's Yes.
是的。
是的。
Yes.
Yes.