无法在复制构造函数中初始化数组
Can not initialize an array in the copy constructor
我有一个class
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
是用循环初始化的。
我有一个class
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
是用循环初始化的。