当前位置:网站首页>(p21-p24) unified data initialization method: List initialization, initializing objects of non aggregate type with initialization list, initializer_ Use of Lisy template class
(p21-p24) unified data initialization method: List initialization, initializing objects of non aggregate type with initialization list, initializer_ Use of Lisy template class
2022-06-12 08:27:00 【Ordinary people who like playing basketball】
List of articles
1. Unified initialization : List initialization
stay C++98/03 in , Corresponding to ordinary arrays and can be directly copied in memory (memcpy ()) The object of can be used List initialization To initialize the data
// Initialization of an array
int array[] = {
1,3,5,7,9 };
double array1[3] = {
1.2, 1.3, 1.4 };
// Object initialization
struct Person
{
int id;
double salary;
}zhang3{
1, 3000 };
stay C++11 in , List initialization has become more flexible , Let's take a look at the following code for initializing class objects
- eg:
#include <iostream>
using namespace std;
class Test
{
public:
Test(int) {
}
private:
Test(const Test &);
};
int main(void)
{
//t1: The most regular initialization method , Initialize the object through the provided structure with parameters
Test t1(520);
/* Grammar mistakes , Because the copy constructor provided is private . If the copy constructor is public ,520 Will be converted by implicit type conversion Test(int) Construct an anonymous object , Then, the anonymous object is copied and constructed t2 The mistake is VS It doesn't show up in , stay Linux Use in g++ The compiler will prompt the error described , The screenshot is as follows ps:vs It is useless to define the copy construct and the equal sign operator as private in , Unless used explicit */
Test t2 = 520;
/* t3 and t4: Used C++11 To initialize objects , Effect and t1 In the same way . In the beginning ,{} Whether the preceding equal sign is written or not has no effect on the initialization behavior . t3 Although the equal sign is used , But it is still list initialization , So private copy constructs have no effect on it . */
Test t3 = {
520 };
Test t4{
520 };
//t1、arr1 and t2、arr2: These two are the list initialization methods of basic data types , You can see , And object initialization methods are unified .
int a1 = {
1314 };
/* t4、a2、arr2 Writing , yes C++11 New syntax format added in , In this way, you can directly follow the initialization list after the variable name , To initialize variables or objects . */
int a2{
1314 };
int arr1[] = {
1, 2, 3 };
int arr2[]{
1, 2, 3 };
// Use list initialization to new Operator creates a new object for initialization
/* The pointer p Points to a new The memory returned by the operator , Initialize the memory data to... Through list initialization 520 Variable b After using the initial list for anonymous objects , And then copy initialization . Array array A block of memory is dynamically allocated on the heap , The initialization of multiple elements is directly completed through list initialization . */
int * p = new int{
520};
double b = double{
52.134};
int * array = new int[3]{
1,2,3};
return 0;
}
- test :

besides , List initialization can also be used directly on the return value of the function :
- eg:
#include <iostream>
#include <string>
using namespace std;
class Person
{
public:
Person(int id, string name)
{
cout << "id: " << id << ", name: " << name << endl;
}
};
Person func()
{
// In code return { 9527, " Hua an " }; Equivalent to return (9527, " Hua an " );, An anonymous object is returned directly
return {
9527, " Hua an " };
}
int main(void)
{
Person p = func();
return 0;
}
- test :

2. List initialization details
Polymer
- stay C++11 in , The use of list initialization has been greatly enhanced , But some vague concepts also follow , As you can see from the previous example , List initialization can be used to initialize custom types , But for a custom type , List initialization may have two execution results
- eg:
#include <iostream>
#include <string>
using namespace std;
struct T1
{
int x;
int y;
}a = {
123, 321 };
struct T2
{
int x;
int y;
T2(int, int) : x(10), y(20) {
}
}b = {
123, 321 };
int main(void)
{
cout << "a.x: " << a.x << ", a.y: " << a.y << endl;
cout << "b.x: " << b.x << ", b.y: " << b.y << endl;
return 0;
}
- test :

In the above programs, the objects are initialized in the form of list initialization , But the result is different , object b Not initialized by data in initialization list , Why is that ?
- object a Is to initialize a custom aggregate type , It will use the data in the initialization list as a copy to initialize T1 Members of the structure .
- In structure T2 A constructor is customized in , So the actual initialization is done through this constructor .
It is also a custom structure and uses list initialization to initialize objects when creating objects , Why are objects initialized differently within a class ?
- Because if you use list initialization to initialize objects , You also need to determine whether the type corresponding to this object is a polymer , The data in the initialization list will be copied to the object .
Use List initialization when , For what type C++ I think it is a polymer ?
- An ordinary array itself can be seen as an aggregate type
int x[] = {
1,2,3,4,5,6};
double y[3][3] = {
{
1.23, 2.34, 3.45},
{
4.56, 5.67, 6.78},
{
7.89, 8.91, 9.99},
};
char carry[] = {
'a', 'b', 'c', 'd', 'e', 'f'};
std::string sarry[] = {
"hello", "world", "nihao", "shijie"};
Classes that meet the following conditions (class、struct、union) Can be seen as an aggregation type :
No user-defined constructor .
Unselfish or protected non static data members .
- scene 1: Class has private members , Cannot initialize with list initialization
struct T1
{
int x;
long y;
protected:
int z;
}t{
1, 100, 2}; // error, Class has private members , Cannot initialize with initialization list
- scene 2: Class has non static members that can be initialized through list initialization , But it cannot initialize static member variables .
struct T2
{
int x;
long y;
protected:
// Static variables in the structure z Cannot initialize with list initialization , Its initialization follows the static member initialization method .
static int z;
}t{
1, 100, 2}; // error
No base class .
No virtual function .
Class cannot have use {} and = Directly initialized non static data members ( from c++14 From the beginning ).
- from C++14 Start , Using list initialization can also be used in classes {} and = Initialized non static data members .
#include <iostream>
#include <string>
using namespace std;
struct T2
{
int x;
long y;
protected:
static int z;
}t1{
1, 100 }; // ok
// Initialization of static members
int T2::z = 2;
struct T3
{
int x;
double y = 1.34;
int z[3]{
1,2,3};
};
int main(void)
{
T3 t{
520, 13.14, {
6,7,8}}; // error, c++11 I won't support it , from c++14 From the beginning
return 0;
}
Non polymer
For classes of aggregate type, you can directly use list initialization to initialize objects , It is also possible to use list initialization if the aggregation conditions are not met
- You need to customize a constructor inside the class , Class member variables are initialized in the constructor using the initialization list :
#include <iostream>
#include <string>
using namespace std;
struct T1
{
int x;
double y;
// Initializing class members with an initialization list in the constructor
T1(int a, double b, int c) : x(a), y(b), z(c){
}
virtual void print()
{
cout << "x: " << x << ", y: " << y << ", z: " << z << endl;
}
private:
int z;
};
int main(void)
{
T1 t{
520, 13.14, 1314 }; // ok, Class members are initialized using the initialization list based on the constructor
t.print();
return 0;
}
- test :

in addition , It should be noted that the definition of aggregate types is not recursive , That is to say When a non static member of a class is a non aggregate type , This class may also be an aggregate type , For example, the following example :
#include <iostream>
#include <string>
using namespace std;
struct T1
{
int x;
double y;
private:
int z;
};
struct T2
{
/* You can see ,T1 Not an aggregate type , Because it has a Private Non static members of . But even though T2 There is a non static member of non aggregate type t1,T2 Still an aggregate type , You can use list initialization directly . */
T1 t1;
long x1;
double y1;
};
int main(void)
{
/* Just to finish up t2 Object initialization process , For members of non aggregate types t1 When doing initialization , You can write a pair of empty braces directly {}, This is equivalent to calling T1 The parameterless constructor for . */
T2 t2{
{
}, 520, 13.14 };
return 0;
}
For an aggregate type , Using list initialization is equivalent to assigning values to each of the elements , For non aggregate types , You need to customize an appropriate constructor first , At this point, using list initialization will call its corresponding constructor .
3.std::initializer_list
- stay C++ Of STL In the container , You can initialize data of any length , The initialization list can only be used to initialize fixed parameters , If you want to do and STL It also has the ability to initialize with any length , have access to std::initializer_list This lightweight class template is used to implement .
- std::initializer_list Characteristics of class template :
It is a lightweight container type , Internally defined iterators iterator And so on , Iterators obtained during traversal are read-only .
about std::initializer_list for , It can receive initialization lists of any length , But the element must be of the same type T
stay std::initializer_list There are three internal member interfaces :size(), begin(), end().
std::initializer_list Objects can only be initialized or assigned as a whole .
As an ordinary function parameter
- Receive any number of parameters of the same type
- If you want to customize a function and accept any number of parameters ( Argument function ), You only need to specify the function parameter as std::initializer_list, Use initialization list { } You can pass data as an argument .
- eg:
#include <iostream>
#include <string>
using namespace std;
void traversal(std::initializer_list<int> a)
{
for (auto it = a.begin(); it != a.end(); ++it)
{
cout << *it << " ";
}
cout << endl;
}
int main(void)
{
initializer_list<int> list;
cout << "current list size: " << list.size() << endl;
traversal(list);
list = {
1,2,3,4,5,6,7,8,9,0 };
cout << "current list size: " << list.size() << endl;
traversal(list);
cout << endl;
list = {
1,3,5,7,9 };
cout << "current list size: " << list.size() << endl;
traversal(list);
cout << endl;
// Pass data directly through the initialization list , The initialization list can be viewed as an object //
traversal({
2, 4, 6, 8, 0 });
cout << endl;
traversal({
11,12,13,14,15,16 });
cout << endl;
return 0;
}
- test :

As a constructor parameter
- If a custom class wants to receive any number of arguments when constructing an object , The constructor can be specified as std::initializer_list type , The container is also used inside the custom class to store the received multiple arguments .
- eg:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Test
{
public:
Test(std::initializer_list<string> list)
{
for (auto it = list.begin(); it != list.end(); ++it)
{
cout << *it << " ";
m_names.push_back(*it);
}
cout << endl;
}
private:
vector<string> m_names;
};
int main(void)
{
Test t({
"jack", "lucy", "tom" });
Test t1({
"hello", "world", "nihao", "shijie" });
return 0;
}
test :

Reference resources : List initialization
边栏推荐
- The residual pressure monitoring system ensures the smoothness of the fire evacuation passage in case of fire, and protects the safe operation of large high-rise buildings and the safety of people's l
- C语言printf输出整型格式符简单总结
- (P40-P41)move资源的转移、forward完美转发
- (P33-P35)lambda表达式语法,lambda表达式注意事项,lambda表达式本质
- (P19-P20)委托构造函数(代理构造函数)和继承构造函数(使用using)
- Instructions spéciales pour l'utilisation du mode nat dans les machines virtuelles VM
- (P13)final关键字的使用
- Never use MES as a tool, or you will miss the most important thing
- 报错:清除网站内搜索框中的历史记录?
- Vision Transformer | Arxiv 2205 - TRT-ViT 面向 TensorRT 的 Vision Transformer
猜你喜欢

Principle and configuration of MPLS

What should be paid attention to when establishing MES system? What benefits can it bring to the enterprise?

如何理解APS系统的生产排程?

Convolutional neural network CNN based cat dog battle picture classification (tf2.1 py3.6)

Model Trick | CVPR 2022 Oral - Stochastic Backpropagation A Memory Efficient Strategy

APS究竟是什么系统呢?看完文章你就知道了

MATLAB image processing - Otsu threshold segmentation (with code)

Hands on deep learning -- activation function and code implementation of multi-layer perceptron

Regular expressions in JS

Hands on learning and deep learning -- simple implementation of softmax regression
随机推荐
记Date类型的一次踩坑
Only use MES as a tool? Looks like you missed the most important thing
Call method and apply method
Vision Transformer | CVPR 2022 - Vision Transformer with Deformable Attention
MES帮助企业智能化改造,提高企业生产透明度
安科瑞消防应急照明和疏散指示系统
Why should enterprises implement MES? What are the specific operating procedures?
(P40-P41)move资源的转移、forward完美转发
Vscode 调试TS
Prediction of COVID-19 by RNN network
Triggers in MySQL
Vision Transformer | Arxiv 2205 - LiTv2: Fast Vision Transformers with HiLo Attention
What is the beauty of MES equipment management for enterprises?
Bean的作用域
(p25-p26) three details of non range based for loop and range based for loop
Beidou satellite navigation system foundation part 1
Record the treading pit of grain Mall (I)
建立MES系统,需要注意什么?能给企业带来什么好处?
Query in MySQL
FPGA to flip video up and down (SRAM is61wv102416bll)