编程语言
首页 > 编程语言> > Initialization List in C++ - C++ 中的初始化列表

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/

ForeverStrong 发布了468 篇原创文章 · 获赞 1746 · 访问量 103万+ 他的留言板 关注

标签:初始化,const,breadth,int,Initialization,List,C++,length,class
来源: https://blog.csdn.net/chengyq116/article/details/104475159