나는 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
개체의 동적 할당 배열을 만들어야하는 편집 된 것으로 보입니다. 그러나이 방법은 여전히 복사 생성자를 사용하지 않습니다. 이 문제를 어떻게 해결할 수 있습니까?