数组C++的复制和赋值构造函数示例

Copy and assignment constructor for arrays C++ example

本文关键字:构造函数 赋值 C++ 复制 数组      更新时间:2023-10-16

需要一些帮助来为我的代码编写复制和赋值构造函数。我得到一个错误"数组只能用初始值设定项列表初始化"。感谢你的帮助-谢谢!

class B
{
public:
   C **table;
B() 
{
   table = new C *[TABLE_SIZE]();
}
B(const B& other)
{
   table = new C *[TABLE_SIZE](other.table);
   memcpy(table, other.table, sizeof(C *)* TABLE_SIZE);
}
B& operator = (const B& other)
{
  if (this == &other)
  {
    return *this;
  }
  delete[] table;
  table = new C *[TABLE_SIZE](other.table);
  memcpy(table, other.table, sizeof(C *)* TABLE_SIZE);
  return *this;
}
}

我猜这是因为初始化table:的方式

table = new C *[TABLE_SIZE](other.table);
memcpy(table, other.table, sizeof(C *)* TABLE_SIZE);

试试这个插页:

table = new C *[TABLE_SIZE];
memcpy(table, other.table, sizeof(C *)* TABLE_SIZE);

我真的不明白你为什么要初始化数组的值,因为这就是你的memcpy的作用。