#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 & 배열) 작동 방법을 모르겠습니다. 구문을 이해하지만 array.m_length가 어디에서 오는지 이해하지 못합니다. 또한 이러한 값이 IntArray로 반환되는 방법을 이해하지도 않습니다. 도와주세요.복사 생성자 작동 방법
'b = a '는'b.operator = (a)'와 동일하므로'array'라는 매개 변수가 할당의 오른쪽 부분입니다. –
그래, 나는 그 지식이있다. –