调用成员函数的拷贝构造函数

Call copy constructors of member functions

我正在尝试学习 C++,并且必须构建一个代码来学习 class 层次结构。它的构造使得 class A 和 B 具有 has-a 关系并且 class 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 

Class乙:

#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 

和class 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 时,我应该会收到复制构造函数消息,但我认为现在它只是在创建一个新对象。

后续问题:我的 class B 实际上看起来像编辑过的,它必须创建一个动态分配的 C 对象数组。但是这样它仍然没有使用拷贝构造函数。我该如何解决这个问题?

在你的拷贝构造函数中你需要调用成员的拷贝构造函数;例如:

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

如果您没有复制构造函数并让编译器为您生成一个,或者如果您显式添加一个并将其标记为default (例如 A(A const&) = default;) 那么生成的复制构造函数应该为你做正确的事情。

我建议您阅读 the rule of zero

我还建议您阅读有关 copy elision 的内容。