无法初始化复制构造函数中的数组

Can not initialize an array in the copy constructor

本文关键字:数组 构造函数 复制 初始化      更新时间:2023-10-16

我有一个类

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

上面,tableNamecountRows 是使用列表初始化的,而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;
}