关于C++11静态成员变量的类内初始化

关于C++11静态成员变量的类内初始化

先放测试后得到的结论,如下表所示。

静态成员变量类型是否可以类内初始化
static int不可以
static const int可以
static const float不可以
static constexpr int必须

总的来说,只有在以下两种情况下,静态成员变量才可以在类内初始化。

  • 使用const修饰的静态整型变量:比如static const int | char | long等。
  • 使用constexpr修饰的所有静态变量:比如static constexpr int | float | double等。

注:第二种类型的变量必须在类内进行初始化。 此外,非静态成员变量不能用constexpr修饰。

测试代码如下:

class ConstTest {
public:
    /*
    	报错: ISO C++ forbids in-class initialization of non-const static member 'ConstTest::a' 
    	解释: 非常量静态成员不能在类内初始化
    */
    static int a = 1;      				// true
    
    /*
    	报错: 'constexpr' needed for in-class initialization of static data member 'float ConstTest::b' of non-integral type
    	解释: 非整形类型的静态数据成员若要在类内初始化, 必须加上关键字constexpr
    */
    static float 	   b = 0.1;       	// false
    static const float c = 0.1;    		// false
    
    /*
    	报错: 'constexpr' static data member 'd' must have an initializer
    	解释: constexpr静态数据成员必须要在类内初始化
    */
    static constexpr float d;			// false
    
    static const int e = 1;        		// true
    static constexpr int f = 1;			// true
    static constexpr float g = 0.1;		// true
    static const int h;					// true
};

const int ConstTest::h = 1;
  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值