无法初始化拷贝构造函数
问题描述:
数组我有一个类无法初始化拷贝构造函数
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)
。如何初始化一个数组?随着变量的发展,一切都很好。谢谢。
答
由于原材料阵列的复制,这样一来,使用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;
}
答
您的代码不会双重任务:除了复制在构造函数体,它还会复制在初始化列表。
您不必这样做:保留可以由列表中的初始化程序列表复制的项目,并将它们从主体中删除;从初始化列表中删除其他项目:
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
与体内循环初始化英寸
std :: array行中的错误;未完成类型 –
Xom9ik
使用'#include'并确保'TRow'在使用之前进行竞争性声明。 –
user0042
谢谢。这就是我需要的 – Xom9ik