#include <iostream>
#include <cassert> // for assert
class IntArray
{
private:
int m_length = 0;
int *m_array = nullptr;
public:
IntArray(int length):
m_length(length)
{
if (length <= 0)
assert("IntArray length should be a positive integer");
m_array = new int[m_length] { 0 };
}
// Copy constructor that does a deep copy
IntArray(const IntArray &array):
m_length(array.m_length)
{
// Allocate a new array
m_array = new int[m_length];
// Copy elements from original array to new array
for (int count = 0; count < array.m_length; ++count)
m_array[count] = array.m_array[count];
}
~IntArray()
{
delete[] m_array;
}
// If you're getting crazy values here you probably forgot to do a deep copy in your copy constructor
friend std::ostream& operator<<(std::ostream &out, const IntArray &array)
{
for (int count = 0; count < array.m_length; ++count)
{
std::cout << array.m_array[count] << ' ';
}
return out;
}
int& operator[] (const int index)
{
assert(index >= 0);
assert(index < m_length);
return m_array[index];
}
// Assignment operator that does a deep copy
IntArray& operator= (const IntArray &array)
{
// self-assignment guard
if (this == &array)
return *this;
// If this array already exists, delete it so we don't leak memory
delete[] m_array;
m_length = array.m_length;
// Allocate a new array
m_array = new int[m_length];
// Copy elements from original array to new array
for (int count = 0; count < array.m_length; ++count)
m_array[count] = array.m_array[count];
return *this;
}
};
IntArray fillArray()
{
IntArray a(5);
a[0] = 5;
a[1] = 8;
a[2] = 2;
a[3] = 3;
a[4] = 6;
return a;
}
int main()
{
IntArray a = fillArray();
// If you're getting crazy values here you probably forgot to do a deep copy in your copy constructor
std::cout << a << '\n';
IntArray b(1);
a = a;
b = a;
// If you're getting crazy values here you probably forgot to do a deep copy in your assignment operator
// or you forgot your self-assignment check
std::cout << b << '\n';
return 0;
}
所以我试图理解这段代码。我知道将为IntArray a = FillArray()调用复制构造函数。但是我不知道IntArray(const IntArray&amp; array)是如何工作的。我理解语法,但不明白array.m_length的来源。我也不理解这些值是如何返回到IntArray的。请帮忙。
答案 0 :(得分:0)
m_length
是类型为“int”的类成员。
此代码:
IntArray(const IntArray &array): m_length(array.m_length)
声明一个名为“array”的参数的函数。分号表示构造函数初始值设定项列表。 m_length
是一个类成员,在此列表中构造出来。 m_length
是一个“int”,因此在调用此函数时会自动调用int的复制构造函数。 array.m_length
来自“数组”,它是在复制构造函数中传递的参数。
答案 1 :(得分:0)
我理解语法,但不明白
array.m_length
的位置 来自。
您在函数IntArray(const IntArray &array)
中,因此array
是引用参数(即赋值/初始化的右侧参数),array.m_length
是成员变量{引用的m_length
对象的{1}}。
我也不了解这些值如何返回到IntArray a。 请帮忙。
同样,在复制构造函数中,您已初始化成员变量IntArray
(m_length
),然后分配成员m_array:
:m_length(array.m_length
当执行语句// Allocate a new array
m_array = new int[m_length];
// Copy elements from original array to new array
for (int count = 0; count < array.m_length; ++count)
m_array[count] = array.m_array[count];
时,fillArray()
返回的数组的成员变量的值如何分配给a
的相应成员变量。