【C++】静态类成员

类中静态成员的特点是:无论创建了多少对象,程序都只创建一个静态类变量副本。也就是说,类的所有对象共享同一个静态成员,就像家中的电话可被全体家庭使用一样。
但是注意,不能在类声明中初始化静态成员变量,这是因为类声明描述了如何分配内存,但并不分配内存。
但是一种例外情况是,静态数据成员为整型const或枚举型const。
(请注意这里,C++primer plus里说的是:但是一种例外情况是,静态数据成员为整型或枚举型const。这里应该是个病句,具有二义性,我一度以为说的是整型或者枚举型const,但是怎么实验都过不去,后来才突然看懂这句话的实际意思是整型const或者枚举型const)

关于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;

猜你喜欢

转载自blog.csdn.net/weixin_43717839/article/details/130026826