拷贝构造函数继承动态分配数组
Copy constructor inheritance dynamically allocated array
我有以下 class 需要创建一个复制构造函数来复制一个动态分配的数组。但是,在下面的代码中,它使用了 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
我的 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
How do I fix this?
好吧,你不需要。在这种情况下,这是正确的行为。因为做的时候需要深拷贝
array = new C[len];
在 B
的复制构造函数中,您默认构造 len
个 C
的内存位置 new
给您。然后,您在
中调用了 C
len
次的复制赋值运算符
for(int i=0;i<len;i++)
{
array[i] = other.array[i];
}
此行将调用 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 */
}
我有以下 class 需要创建一个复制构造函数来复制一个动态分配的数组。但是,在下面的代码中,它使用了 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
我的 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
How do I fix this?
好吧,你不需要。在这种情况下,这是正确的行为。因为做的时候需要深拷贝
array = new C[len];
在 B
的复制构造函数中,您默认构造 len
个 C
的内存位置 new
给您。然后,您在
C
len
次的复制赋值运算符
for(int i=0;i<len;i++)
{
array[i] = other.array[i];
}
此行将调用 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 */
}