【问题标题】:Call copy constructors of member functions调用成员函数的复制构造函数
【发布时间】:2017-09-07 21:49:36
【问题描述】:

我正在尝试学习 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 时,我应该得到复制构造函数的消息,但现在我认为它只是创建一个新对象。

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

【问题讨论】:

    标签: c++ class inheritance copy-constructor


    【解决方案1】:

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

    我建议你阅读the rule of zero

    我还建议您阅读copy elision

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-03-06
        • 1970-01-01
        • 1970-01-01
        • 2011-12-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多