[C++] Talk about initialization list

foreword

Initializer List: Starts with a colon, followed by a comma-separated list of data members, each "member variable" followed by an initial value or expression in parentheses.

1. How to initialize member variables

Take a look at the tree node code of an AVL tree

We know that there are several ways to initialize the member variables of the class

  • Initialize inside the constructor
template<class K, class V>
struct AVLTreeNode{
    
    
	pair<K, V> _kv;
	int _bf; // balance factor = h(subRight) - h(subLeft)
	AVLTreeNode<K, V>* _parent;
	AVLTreeNode<K, V>* _left;
	AVLTreeNode<K, V>* _right;
	
AVLTreeNode(const pair<K, V>& kv) {
    
    
	_kv = kv;
	_bf = 0;
	_parent = nullptr;
	_left = nullptr;
	_right = nullptr;
};
  • give default value
template<class K, class V>
struct AVLTreeNode{
    
    
	pair<K, V> _kv = kv;
	int _bf = 0; // balance factor = h(subRight) - h(subLeft)
	AVLTreeNode<K, V>* _parent = nullptr;
	AVLTreeNode<K, V>* _left = nullptr;
	AVLTreeNode<K, V>* _right = nullptr;

	AVLTreeNode(const pair<K, V>& kv)
	{
    
    }
};
  • initialization list
```cpp
template<class K, class V>
struct AVLTreeNode{
    
    
	pair<K, V> _kv;
	int _bf; // balance factor = h(subRight) - h(subLeft)
	AVLTreeNode<K, V>* _parent;
	AVLTreeNode<K, V>* _left;
	AVLTreeNode<K, V>* _right;

	AVLTreeNode(const pair<K, V>& kv)
		:_kv(kv)
		,_bf(0)
		,_parent(nullptr)
		,_left(nullptr)
		,_right(nullptr)
	{
    
    }
};

2. Notes and advantages of initialization list

1. Each member variable can only appear once in the initialization list (initialization can only be initialized once)

2. The class contains the following members, which must be initialized in the initialization list:

  • reference member variable
  • const member variable
  • Custom type members (the class has no default constructor)
class A
{
    
    
public:
	A(int a)
		:_a(a)
	{
    
    }
private:
	int _a;
};
class B
{
    
    
public:
	B(int a, int ref)
		:_aobj(a)
		,_ref(ref)
		,_n(10)
	{
    
    }
private:
	A _aobj; // 没有默认构造函数
	int& _ref; // 引用
	const int _n; // const
};

Advantage:

Try to use initialization list initialization, because whether you use initialization list or not, for custom type member variables, you must use initialization list initialization before calling the constructor

insert image description here

Guess you like

Origin blog.csdn.net/m0_52640673/article/details/123219988