Initialization List in C++ - C++ 中的初始化列表

Initialization List in C++ - C++ 中的初始化列表

1. Initialization List in C++

In the previous chapter, we learned about how classes and their objects can be created and the different ways their members can be accessed. We also saw how data members are initialized in the constructor of any class as shown below.
在上一章中,我們瞭解瞭如何創建類及其對象以及如何訪問其成員的不同方式。我們還看到了如何在任何類的構造函數中初始化數據成員,如下所示。

//============================================================================
// Name        : std::class
// Author      : Yongqiang Cheng
// Version     : Version 1.0.0
// Copyright   : Copyright (c) 2019 Yongqiang Cheng
// Description : Hello World in C++, Ansi-style
//============================================================================

class Rectangle
{
	int length;
	int breadth;
public:
	Rectangle()
	{
		length = 7;
		breadth = 4;
	}
};

In the above constructor, we assigned the values 7 and 4 to the data members length and breadth respectively. Note that, here we assigned the values to these variables, not initialized.
在上述構造函數中,我們分別將值 7 和 4 分配給了數據成員的 lengthwidth。請注意,此處我們將值分配給了這些變量,但未初始化。

In the case of constructors having parameters, we can directly initialize our data members using initialization lists.
在構造函數具有參數的情況下,我們可以使用初始化列表直接初始化數據成員。

Using initialization list, we can write the above code as follows.
使用初始化列表,我們可以將上面的代碼編寫如下。

//============================================================================
// Name        : std::class
// Author      : Yongqiang Cheng
// Version     : Version 1.0.0
// Copyright   : Copyright (c) 2019 Yongqiang Cheng
// Description : Hello World in C++, Ansi-style
//============================================================================

class Rectangle
{
	int length;
	int breadth;
public:
	Rectangle() : length(7), breadth(4) // initializing data members
	{
		// no need to assign anything here
	}
};

An initializer list starts after the constructor name and its parameters and begins with a colon (:) followed by the list of variables which are to be initialized separated by a comma with their values in curly brackets.
初始化列表以構造函數名稱及其參數之後開始,並以冒號 (:) 開始,後跟要初始化的變量列表,逗號分割,用大括號括起來。

curly [ˈkɜːli]:adj. 捲曲的,捲毛的,(木材) 有皺狀紋理的,蜷縮的

Let’s see an example for the above code.

//============================================================================
// Name        : std::class
// Author      : Yongqiang Cheng
// Version     : Version 1.0.0
// Copyright   : Copyright (c) 2019 Yongqiang Cheng
// Description : Hello World in C++, Ansi-style
//============================================================================

#include <iostream>

using namespace std;

class Rectangle
{
	int length;
	int breadth;
public:
	Rectangle() : length(7), breadth(4)
	{

	}
	int printArea()
	{
		return length * breadth;
	}
};

int main()
{
	Rectangle rt;
	cout << rt.printArea() << endl;

	return 0;
}

Output

28

Here we initialized the variables length and breadth directly using an initializer list in which we length and breadth were initialized to 7 and 4 respectively.
在這裏,我們使用初始化列表直接初始化變量 lengthwidth,其中 lengthwidth 分別被初始化爲 7 和 4。

The rest of the code is the same.
其餘代碼相同。

Let’s see another example of initialization list in case of parameterized constructor.
讓我們看一下在使用參數化構造函數的情況下初始化列表的另一個示例。

//============================================================================
// Name        : std::class
// Author      : Yongqiang Cheng
// Version     : Version 1.0.0
// Copyright   : Copyright (c) 2019 Yongqiang Cheng
// Description : Hello World in C++, Ansi-style
//============================================================================

#include <iostream>

using namespace std;

class Rectangle
{
	int length;
	int breadth;
public:
	Rectangle(int l, int b) : length(l), breadth(b)
	{

	}

	int printArea()
	{
		return length * breadth;
	}
};

int main()
{
	Rectangle rt(7, 4);
	cout << rt.printArea() << endl;

	return 0;
}

Output

28

In this example, the initializer list is directly initializing the variables length and breadth with the values of l and b which are 7 and 4 respectively.
在此示例中,初始化程序列表直接使用 lb 的值 (分別爲 7 和 4) 初始化變量 lengthwidth

This is the same as the following code with the only difference that in the above example, we are directly initializing the variables while in the following code, the variables are being assigned the parameterized values.
這與下面的代碼相同,唯一的不同是在上面的示例中,我們直接初始化變量,而在下面的代碼中,變量被分配了參數化值。

//============================================================================
// Name        : std::class
// Author      : Yongqiang Cheng
// Version     : Version 1.0.0
// Copyright   : Copyright (c) 2019 Yongqiang Cheng
// Description : Hello World in C++, Ansi-style
//============================================================================

class Rectangle
{
	int length;
	int breadth;
public:
	Rectangle(int l, int b)
	{
		length = l;
		breadth = b;
	}
};

2. Need for Initialization List

Though we can use initialization list anytime as we did in the above examples, but there are certain cases where we have to use initialization list otherwise the code won’t work.
儘管我們可以像上面的示例一樣隨時使用初始化列表,但是在某些情況下,我們必須使用初始化列表,否則代碼將無法工作。

If we declare any variable as const, then that variable can be initialized, but not assigned.
如果我們將任何變量聲明爲 const,則該變量可以初始化,但不能賦值。

Any variable declared with const keyword before its data type is a const variable.
在數據類型之前用 const 關鍵字聲明的任何變量都是 const 變量。

To initialize a const variable, we use initialization list. Since we are not allowed to assign any value to a const variable, so we cannot assign any value in the body of the constructor. So, this is the case where we need initialization list.
要初始化 const 變量,我們使用初始化列表。由於不允許將任何值分配給 const 變量,因此我們不能在構造函數的主體中分配任何值。因此,在這種情況下,我們需要初始化列表。

Following is an example initializing a const data member with initialization list.
以下是使用初始化列表初始化 const 數據成員的示例。

//============================================================================
// Name        : std::class
// Author      : Yongqiang Cheng
// Version     : Version 1.0.0
// Copyright   : Copyright (c) 2019 Yongqiang Cheng
// Description : Hello World in C++, Ansi-style
//============================================================================

#include <iostream>

using namespace std;

class Rectangle
{
	const int length;
	const int breadth;
public:
	Rectangle(int l, int b) : length(l), breadth(b)
	{

	}
	int printArea()
	{
		return length * breadth;
	}
};

int main()
{
	Rectangle rt(7, 4);
	cout << rt.printArea() << endl;

	return 0;
}

Output

28

In this example, the variables length and breadth are declared as constant and thus cannot be assigned any value in the body of the constructor. So, we initialized them in the initializer list.
在此示例中,變量 lengthwidth 聲明爲常量,因此無法在構造函數的主體中爲其分配任何值。因此,我們在初始化器列表中對其進行了初始化。

If we try to assign values to a const variable, we will get an error. We will learn more about the const keyword in a later chapter.
如果嘗試將值分配給 const 變量,則會收到錯誤消息。在下一章中,我們將更多地瞭解 const 關鍵字。

One more case where we need initializer list is when we want to initialize base class members by creating an object of the subclass. We will see this in the next chapter.
我們需要初始化器列表的另一種情況是,我們想通過創建子類的對象來初始化基類成員。我們將在下一章中看到。

There may be some other cases too where we would need initializer list but we can always use it as an alternative even when it’s not necessary.
在其他情況下,我們也需要初始化器列表,但是即使沒有必要,我們也可以始終將其用作替代項。

inheritance [ɪnˈherɪtəns]:n. 繼承,遺傳,遺產
class:類
derived class:繼承類,派生類
subclass:子類
base class:基類
superclass:超類,父類
passion [ˈpæʃn]:n. 激情,熱情,酷愛,盛怒
muscle [ˈmʌsl]:n. 肌肉,力量 vt. 加強,使勁搬動,使勁擠出 vi. 使勁行進

References

https://www.codesdope.com/cpp-initialization-list/

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章