-3

동적 메모리 할당을 배우고 있습니다. 나는 '클래스 A'가 생성자에서 동적으로 할당 된 배열을 소유해야하는 다음 클래스를 가지고있다. 또한 복사 생성자와 소멸자를 수정해야합니다. 이것은 내가 지금까지 무엇을 가지고 ...생성자의 동적 메모리 할당

기본 생성자 동일한 유형의 지역 변수와 멤버 변수 "배열"이 무시된다 우선 들어
#include <iostream> 
#ifndef A_HH 
#define A_HH 

#include "B.hh" 

class A { 
public: 

    A() { B *array = new B[12];} 
    A(const A&) { /* Do not know what to put here..*/ } 
    ~A() { delete[] array;} 

private: 

    //B array[12] ; <- This is the array that I have to modify so it becomes dynamic. 
    B *array; 
} ; 

#endif 
+0

로를 제쳐두고,'#include '을 헤더 가드 안에 넣어야합니다. – LiamT

+0

당신은 [규칙 3] (http://stackoverflow.com/questions/4172722/what-is-the-rule-of-three)에 익숙해 져야합니다 (또는 C++ 11, [rule of five] (http://stackoverflow.com/questions/4782757/rule-of-three-becomes-rule-of-five-with-c11)). 또한 [복사본 및 스왑 숙어] (http://stackoverflow.com/questions/3279543/what-is-the-copy-and-swap-idiom)를 살펴볼 수도 있습니다. – Aconcagua

답변

1

, 그래서 당신은 기본 생성자는 다음과 같이 할 :

A() { array = new B[12]; } 

그런 다음 복사 생성자는 아마도 배열을 통해 깊은 사본이 필요하지만 간단한 배열과 런타임에 arraysize 말할 수 없습니다. 당신도 스마트 컨테이너 (예 : STL :: 벡터)로 이동하거나 크기를 저장해야하지만, 순진 복사 생성자는 다음과 같이 보일 것이다 :

A(const A& other) 
{ 
    array = new B[12]; 
    for(int i=0;i<12;i++) 
    { 
     array[i] = other.array[i]; 
    } 
} 
+1

배열 크기를 12로 하드 코딩하는 것은 정말 나쁜 생각인데, 적어도 #define 또는 static const int를 어딘가에 추가하는 것이 좋습니다. –

+0

"#define 또는 정적 const int 추가"로 정확히 무엇을 의미합니까? 나는 이런 종류의 물건에 대해 거의 경험이 없다. ;) –

+0

당신의 배열이 항상 크기가 12이고 클래스 안에 있다면'static const int ARRAY_SIZE = 12;'를 추가하십시오. 그러면 12를 넣을 때마다 대신 ARRAY_SIZE를 넣으십시오. 이 배열의 길이가 가변 인 경우에는 필요하지 않습니다. –

-1

체크 아웃이 코드 :

#include <iostream> 


using namespace std; 

class MyArray{ 
public: 
    int* array; 
    int length; 

    MyArray(int length){ // constructor which takes length of array as argument 
     this->length = length; 
     this->array = new int[this->length]; 

     for(int i=0; i<this->length; i++){ 
      this->array[i] = i; 
     } 
    } 

    MyArray(const MyArray &obj){ 
     this->length = obj.length; 
     this->array = new int[this->length]; 
     for(int i=0; i<this->length; i++) 
     { 
      this->array[i] = obj.array[i]; 
     } 
    } 

    ~MyArray(){ // destructor 
     delete[] this->array; 
    } 


    void print(){ // test method for printing the array 
    for(int i=0; i<this->length; i++){ 
      cout << this->array[i] << endl; 
     } 
     cout << endl; 
    } 

private: 
protected: 

}; 
int main() 
{ 
    MyArray *array = new MyArray(10); 
    MyArray *array2 = new MyArray(*array); // call copy constructor 

    array->print(); 
    array2->print(); 

    delete array; 
    delete array2; 
} 
+1

이 인스턴스의 array 및 array2는 복사 생성자가 새로운 개별 배열이 아니라 포인터를 복사 할 때와 동일한 버퍼를 가리 킵니다. 파괴시 충돌이 발생합니다. –

+0

테스트를 받았는데 충돌이 없었습니까? 내가 편집하고 깊은 배열 복사본을 추가합니다. –

+0

나는 그것을 언급하기위한 깊은 사본 .. thx 코드를 변경했습니다! –