[C++] Initialization of member variables in a class

1. Member type

For a class, there are generally four member types

class MyClass
{
public:
	MyClass();
	~MyClass();

private:
	int a ; 变量(非静态变量)
	const int b; 常量(非静态常量) error
	static int c; 静态变量
	static const int d; 静态常量
};

Note: For non-static constant b, it needs to be initialized.

2. Initialization

C++98

Constants and variables need to be initialized in the constructor, and static constants can be initialized in the class. Just understand it here, after all, it is generally C++11;

In C++11, C++98 has been improved .

Constants, variables, static constants --- can be initialized within the class

Static variables --- cannot be initialized within a class. as follows

	int a =1;
	const int b=2;
	static int c=3;错误
	static const int d=4;
//错误    C2864    MyClass::c: 带有类内初始化表达式的静态 数据成员 必须具有不可变的常量整型类型,

Note: The meaning of the error is that to initialize a static member in a class, it must be a static constant (d), but a static variable (c) cannot.

Because a static member belongs to the entire class, not to an object, if it is initialized within the class, it will cause every object to contain the static member, which is contradictory

Static constant members can be declared inside a class

3. Initialization method

In C++11, when defining a class, it is allowed to directly initialize non-static members and static member constants in the class using "=()" and "{ }". as follows

class MyClass
{
public:
	MyClass();
	~MyClass();

private:
	int a1 = 1;		//方式一
	int a2 = {2};	//方式二
	int a3{3};		//方式三
	const int b1 = 1;
	const int b2 = {2};
	const int b3{3};
	static int c;	//类外初始化
	static const int d1 = 1;
	static const int d2 = {2};
	static const int d3{3};
};

4. Initialization list

You can use the initialization list to initialize non-static members in the constructor, such as the initialization of a and b

class MyClass
{
public:
	MyClass(int v1,int v2):a(v1),b(v2) {};//初始化列表
	~MyClass() {};

private:
	int a;		
	const int b;
	static int c;	//类外初始化
	static const int d ;

};

5. Summary

In C++11,

1. Non-static constants, non-static variables, static constants --- can be initialized within the class. You can use = () or {}. Static variables --- must be initialized outside the class.

2. Non-static constants (const int) must be initialized. In-class or initializer-list initialization

3. Non-static variables (int) can not be initialized, or can be initialized in the class or initialization list

4. Static constants (static const int) must be initialized outside the class .

5. Static variables ( static int ) may not be initialized, or may be initialized within the class , and the initialization list cannot be used

Guess you like

Origin blog.csdn.net/m0_57168310/article/details/126746229