2016-09-16 5 views
0
#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로 반환되는 방법을 이해하지도 않습니다. 도와주세요.복사 생성자 작동 방법

+0

'b = a '는'b.operator = (a)'와 동일하므로'array'라는 매개 변수가 할당의 오른쪽 부분입니다. –

+0

그래, 나는 그 지식이있다. –

답변

0

m_length는 "int"유형의 클래스 멤버입니다.

이 코드 :

IntArray(const IntArray &array): m_length(array.m_length) 

는 "배열"라는 하나 개의 매개 변수와 함수를 선언합니다. 세미콜론은 생성자 초기화 목록을 나타냅니다. m_length는이 목록에서 생성되도록 호출 된 클래스 멤버입니다. m_length는 "int"이므로이 함수가 호출 될 때 int의 복사 생성자가 자동으로 호출됩니다. array.m_length는 복사 생성자에서 전달되는 인수 인 "array"에서 비롯됩니다.

+0

그래서이 경우 array.m_length는 FillArray()에서 비롯 되었기 때문에 = 5가됩니까? –

+0

함수 FillArray()에서 IntArray 객체는 IntArray 복사 생성자를 사용하여 인스턴스화되며 해당 복사 생성자에서 전달 된 인수는 정수 "5"입니다. 프로그램이 복사 생성자에 들어 오면, 예, array.m_length는 5입니다. –

+0

그래서 복사 생성자 매개 변수가 복사되는 객체에서 가져 오는 것으로 가정하여 앞으로 잘못되거나 잘못 프로그래밍 될 것입니까? –

0

나는 구문을 이해하지만, array.m_length이 인 곳을 이해하지 못한다.

당신 정말 array는 기준 파라미터는 함수 IntArray(const IntArray &array)에 (즉, 우측의 할당/초기화 인수) 및 array.m_length는 멤버 변수 참조 IntArray 객체 m_length이다.

이 값이 IntArray로 어떻게 반환되는지 이해하지 못합니다. 도와주세요.

// 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]; 

회원의 방법 값입니다 :

다시, 복사 생성자, 당신은 다음 멤버 변수 m_length (:m_length(array.m_length)의 초기화 및 회원 m_array의 할당이 문 IntArray a = fillArray()이 실행되면 fillArray()에 의해 반환 된 배열의 변수는 a의 해당 멤버 변수에 할당됩니다.

+0

및 복사 생성자가 호출 될 때 복사되는 개체에서 가져온 해당 생성자의 매개 변수는 무엇입니까? –

+0

복사 생성자에는 하나의 매개 변수 인 복사 할 개체가 있습니다. 당신의 예제에서 :'const IntArray &'. 그런 다음 복사 생성자의 코드에 표현됩니다.그러나 네, 귀하의 경우 (또한 일반적으로 일반적으로) 복사 ctor 않는 복사 (개체의 가치) 복사되는 개체의 각 구성원입니다. 즉, 이러한 값을 사용하여 생성되는 객체의 멤버를 초기화합니다. – drRobertz