数组C++的复制和赋值构造函数示例
Copy and assignment constructor for arrays C++ example
需要一些帮助来为我的代码编写复制和赋值构造函数。我得到一个错误"数组只能用初始值设定项列表初始化"。感谢你的帮助-谢谢!
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
的作用。
相关文章:
- 为什么在使用转换构造函数赋值后调用C++类的析构函数?
- 为用户定义的类正确调用复制构造函数/赋值运算符
- C++:关于使用 Stroustrup 示例移动构造函数/赋值的问题
- 初始值设定项列表与构造函数赋值与变量定义
- std::vector::emplace() 真的在面对抛出移动构造函数/赋值运算符时提供了强大的异常保证吗?
- 创建一个类并在C++中使用构造函数(赋值)
- 如何为具有自引用指针的类实现复制构造函数/赋值运算符
- 使typedef的构造函数/赋值运算符成为友元函数
- 复制构造函数+赋值运算符
- C++ 矢量从构造函数赋值对象,无需临时
- 具有std::原子成员变量的类的复制构造函数/赋值运算符出错
- 初始化对象时复制构造函数/赋值运算符混淆
- 默认情况下是默认的构造函数/赋值noexcept/constexpr
- 模板是否应该为不同类型的参数制作非 Rvalue 引用构造函数/赋值
- 为什么 std 类型不提供来自分配器不同源的转换构造函数/赋值
- 是否为派生类生成的移动构造函数/赋值运算符
- 复制构造函数/赋值运算符
- C++复制构造函数/赋值运算符错误
- 正在获取要使用的移动构造函数/赋值运算符
- 影响正确性的move构造函数/赋值操作符示例