私は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
オブジェクトの動的に割り当てられた配列を作成する必要がある編集済みのものです。しかし、この方法ではまだコピーコンストラクタは使用されません。これをどうやって解決するのですか?