无法初始化复制构造函数中的数组
Can not initialize an array in the copy constructor
我有一个类
class TTable
{
private:
std::string tableName;
public:
TRow rows[10]; //this other class TRow
TTable(const TTable&);
int countRows = 0;
};
我实现了复制构造函数
TTable::TTable(const TTable& table) : tableName(table.tableName), countRows(table.countRows), rows(table.rows)
{
cout << "Copy constructor for: " << table.GetName() << endl;
tableName = table.GetName() + "(copy)";
countRows = table.countRows;
for (int i = 0; i < 10; i++)
{
rows[i] = table.rows[i];
}
}
但是编译器诅咒这个rows(table.rows)
.如何初始化数组?有了变量,一切都会好,一切都很好。谢谢。
你的代码有双重任务:除了在构造函数的主体中复制外,它还在初始化列表中复制。
您不必这样做:将初始值设定项列表可以复制的项目保留在列表中,并将它们从正文中删除;从初始值设定项列表中删除其他项:
TTable::TTable(const TTable& table)
: tableName(table.tableName + "(copy)")
, countRows(table.countRows)
{
cout << "Copy constructor for: " << table.GetName() << endl;
for (int i = 0; i < 10; i++) {
rows[i] = table.rows[i];
}
}
上面,tableName
和 countRows
是使用列表初始化的,而rows
是用 body 中的循环初始化的。
由于原始数组无法以这种方式复制,因此请改用std::aray<TRow,10> rows;
:
class TTable
{
private:
std::string tableName;
public:
std::array<TRow,10> rows;
TTable(const TTable&);
int countRows = 0;
};
TTable::TTable(const TTable& table)
: tableName(table.tableName + "(copy)")
, countRows(table.countRows)
, rows(table.rows) {
cout << "Copy constructor for: " << table.GetName() << endl;
}
相关文章:
- 从数组构造一个跨度<shared_ptr<T>><shared_ptr<void>>
- C++从函数指针数组调用函数
- 是否可以就地构造一个固定大小的数组作为函数参数?
- 节点插件 API 将数组作为函数参数传递
- 将字符串数组作为函数参数传递
- 如何在不使用 C++ 中的数组或函数的情况下查找 N 位数字的所有排列
- C++返回反向字符数组的函数
- 类数组插入函数
- 使用数组数组调用 C++ 函数
- 在 c++ 中将数字转换为矢量数组的函数
- 为什么我的数组或函数不起作用?
- 带有函数指针的数组构造函数
- 对象的数组-STD ::数组 - 构造函数初始化问题
- 将对象类型传递到std ::数组构造函数
- std::initializer_list 作为 std::数组构造函数
- 如何为我的类创建数组构造函数
- Constexpr类与数组构造函数方法
- 列表数组-构造函数和main()中的地址不匹配
- 数组构造函数继承
- 不安全的模板数组构造函数