Copy constructors, Assignment operators, and Copy assignment operator

 1 #include <cassert> // for assert()
 2 #include <initializer_list> // for std::initializer_list
 3 #include <iostream>
 4  
 5 class IntArray
 6 {
 7 private:
 8     int m_length;
 9     int *m_data;
10  
11 public:
12     IntArray() :
13         m_length(0), m_data(nullptr)
14     {
15     }
16  
17     IntArray(int length) :
18         m_length(length)
19     {
20         m_data = new int[length];
21     }
22  
23     IntArray(const std::initializer_list<int> &list): // allow IntArray to be initialized via list initialization
24         IntArray(list.size()) // use delegating constructor to set up initial array
25     {
26         // Now initialize our array from the list
27         printf("initializer_lis start!!!!\n");
28         
29         int count = 0;
30         for (auto &element : list)
31         {
32             m_data[count] = element;
33             ++count;
34         }
35     }
36      IntArray(const IntArray &array)
37     {
38         m_length = array.m_length;
39         m_data = new int[m_length];
40         
41         int i = 0;
42         for (; i < m_length; i++)
43         {
44             m_data[i] = array.m_data[i];
45         }
46     }
47         
48     ~IntArray()
49     {
50         delete[] m_data;
51         // we don't need to set m_data to null or m_length to 0 here, since the object will be destroyed immediately after this function anyway
52     }
53  
54     int& operator[](int index)
55     {
56         assert(index >= 0 && index < m_length);
57         return m_data[index];
58     }
59     void operator=(const std::initializer_list<int> &list)
60     {
61         m_length = list.size();
62         m_data = new int[m_length];
63         int count = 0;
64         for (auto &element : list)
65         {
66             m_data[count] = element;
67             ++count;
68         }
69 
70     }
71     
72     void operator=(const IntArray &array)
73     {
74         m_length = array.m_length;
75         m_data = new int[m_length];
76         
77         int i = 0;
78         for (; i < m_length; i++)
79         {
80             m_data[i] = array.m_data[i];
81         }
82 
83 
84     }
85     int getLength() { return m_length; }
86 };

猜你喜欢

转载自www.cnblogs.com/yetanghanCpp/p/9237829.html