2017-04-12 123 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 

類:

#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類實際上看起來像編輯的類,它必須創建一個動態分配的對象數組。但是這樣它仍然不使用拷貝構造函數。我該如何解決?

回答

2

在您的拷貝構造函數中,您需要調用成員的拷貝構造函數;例如:

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

如果沒有有一個拷貝構造函數,讓編譯器生成一個給你,或你特別添加一個標記爲default(例如像A(A const&) = default;),然後將生成的複製構造函數應該爲你做正確的事情。

我建議你閱讀約the rule of zero

我也推薦你閱讀約copy elision