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

あなたはコピーコンストラクタを持っていると、コンパイラはあなたのための1つを生成させる、または明示的に1を追加し、(例えばA(A const&) = default;のような)defaultとしてそれをマークするならば、生成されませんない場合:たとえば、コピーコンストラクタはあなたのために適切なことを行う必要があります。

the rule of zeroについてお読みください。

copy elisionについて読むことをお勧めします。

関連する問題