2017-04-12 1 views
3

나는 C++을 배우려고 노력 중이며 클래스 계층 구조를 배우기 위해 코드를 작성해야합니다. 그것은 클래스 A와 B가 has-a 관계와 클래스 B와 C를 갖도록 생성되었습니다. A의 복사 생성자가 B와 C의 복사 생성자를 호출 할 수 있도록하여 주 파일에서 객체의 복사본을 만들어야합니다. 하지만 어떻게해야할지 모르겠다.구성원 함수의 호출 복사 생성자

#ifndef A_HH 
#define A_HH 


#include "B.hh" 


class A { 
public: 

    A() { std::cout << "Constructor A" << this << std::endl ; } 
    A(const A&) { std::cout << "Copy Constructor A" << this << std::endl ; } 
    ~A() { std::cout << "Destructor A" << this << std::endl ; } 

private: 


    B b; 

} ; 

#endif 

클래스 B :

#ifndef B_HH 
#define B_HH 

#include <iostream> 

#include "C.hh" 

class B { 
public: 

    B() { std::cout << "Constructor B" << this << std::endl ; array = new C[len];} 
    B(const B& other): array(other.array) { std::cout << "Copy Constructor B" << this << std::endl ; 
    array = new C[len]; 
    for(int i=0;i<len;i++) 
    { 
     C[i] = other.C[i]; 
    } 

    } 
    ~B() { std::cout << "Destructor B" << this << std::endl ; delete[] array;} 

private: 


    C *array; 
    static const int len = 12; 

} ; 

#endif 

그리고 클래스 C :

#ifndef C_HH 
#define C_HH 

#include <iostream> 

class C { 
public: 

    C() { std::cout << "Constructor C" << this << std::endl ; } 
    C(const C&) { std::cout << "Copy Constructor C" << this << std::endl ; } 
    ~C() { std::cout << "Destructor C" << this << std::endl ; } 

private: 

} ; 

#endif 

내가 모두 같은 객체 생성 : 따라서

#include<iostream> 
#include"A.hh" 

int main(){ 


A a; 
A a_clone(a); 
} 

a_clone을 만드는, 내가 가야 카피 생성자 m 그러나 이제는 내가 생각하기에 새로운 대상을 만들고 있습니다.

후속 질문 : 실제로 클래스 B는 C 개체의 동적 할당 배열을 만들어야하는 편집 된 것으로 보입니다. 그러나이 방법은 여전히 ​​복사 생성자를 사용하지 않습니다. 이 문제를 어떻게 해결할 수 있습니까?

답변

2

복사 생성자에서 멤버의 복사 생성자를 호출해야합니다. 예를 들면 :

A::A(const A& rhs): b(rhs.b) {} 
2

그런 다음 생성 된 복사 생성자가 당신이 명시 적으로 (예 : A(A const&) = default; 등) default로 하나를 추가하고 표시 할 경우 컴파일러는 당신을 위해 하나를 생성하거나하지 할 경우 복사 생성자는 당신에게 옳은 일을해야합니다.

나는 the rule of zero에 관해 읽는 것이 좋습니다.

나는 또한 copy elision에 관해 읽는 것이 좋습니다.