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

时间:2015-03-18 23:12:36

标签: c++ constructor copy-constructor

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

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;
}
}

1 个答案:

答案 0 :(得分:0)

我猜这是因为你正在初始化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无论如何。

相关问题