• 关于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;
    
    • 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
  • 相关阅读:
    基于微信小程序的电影院订票系统设计与实现(源码+lw+部署文档+讲解等)
    【JAVA开发规范】日志规范
    工厂模式介绍
    Apache shenyu,Java 微服务网关的首选
    MybatisPlus-环境配置/基本CRUD/常用注解
    kubernetes资源管理
    小项目中怎么防止Vue的闪现画面效果
    Java Reader类简介说明
    SQLZOO——SELECT within SELECT Tutorial
    2022.9.28
  • 原文地址:https://blog.csdn.net/Azahaxia/article/details/126160038