我有以下类,我需要创建一个复制构造函数来复制动态分配数组。但是,在下面的代码中,它使用C的构造函数而不是复制构造函数。我该如何解决这个问题?
#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++)
{
array[i] = other.array[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
答案 0 :(得分:0)
我该如何解决这个问题?
嗯,你不需要。在这种情况下,这是正确的行为。因为你需要做一个深层复制
array = new C[len];
在B
的复制构造函数中,您在内存位置len
中默认构造C
个new
个。然后,您在
C
len
次的复制赋值运算符
for(int i=0;i<len;i++)
{
array[i] = other.array[i];
}
答案 1 :(得分:0)
此行将调用len
个默认C
构造函数
array = new C[len];
然后这一行实际上应该调用复制赋值运算符
array[i] = other.array[i];
将此行添加到C
,您会看到这是一个副本分配
C& operator=(const C&)
{
std::cout << "Copy Assignment Operator C" << this << std::endl;
/* do actual copying here */
}