Copy constructors, Assignment operators, and Copy assignment operator

C++ IntArray 类实现
本文介绍了一个 C++ 实现的 IntArray 类,该类支持通过初始化列表构造、拷贝构造及赋值操作,并提供了下标运算符重载等功能。
 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 };

 

转载于:https://www.cnblogs.com/yetanghanCpp/p/9237829.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值