书法字典:https://www.shufadict.com

only static const integral data members can be initialized within a class

翻译一下:只有静态整型常量数据成员能在类中初始化

那么哪些数据属于整型呢,下面的都是

  • char
  • short
  • int
  • long
  • long long

所以只有以上这些类型的数据能在类中初始化,也就是你可以这样写

1 class Test
2 {
3     static const int i = 100 ;
4 } ;
5 

 

但不能这样写,否则就会出现如标题所示的编译错误。

1 class Test
2 {
3     static const float i = 100.0f ;
4 } ;
5 

因为float不属于integral type,对于float类型可以在类中定义,在类外初始化,如下:

class Test
{
    static const int i = 100 ;
    static const float f;
};

const float Test::f = 1.0f;

 

另外要注意的是,bool也可以在类中初始化,像下面这样

1 class Test
2 {
3     static const bool flag = true ;
4 } ;
5 

但是我却没有找到bool是integral type的说法,bool的值有两种,true和false,对应二进制的0和1,用一个bit就可以表示了,但是C++中长度最短的类型是char,所以只能用char表示,而char属于整型,是不是这样就把bool也归为整型了呢?猜测而已。

另外,C++标准对于哪些类型能在类中初始化有详细的描述,如下:

If a static data member is of const integral or const enumeration type, its declaration in the class definition can specify a constant-initializer which
shall be an integral constant expression

所以不只整型常量可以,枚举常量也可以在类中初始化,像下面这样

复制代码
 1 enum COLOR
 2 {
 3     RED, 
 4     GREEN,
 5     BLUE
 6 } ;
 7 
 8 class Test
 9 {
10     static const COLOR color = GREEN ;
11 } ;
复制代码

 

 

posted on   翰墨小生  阅读(4576)  评论(1编辑  收藏  举报

编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· .NET周刊【3月第1期 2025-03-02】
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· [AI/GPT/综述] AI Agent的设计模式综述

导航

< 2010年3月 >
28 1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31 1 2 3
4 5 6 7 8 9 10
书法字典:https://www.shufadict.com
点击右上角即可分享
微信分享提示