无法在复制构造函数

时间:2017-10-07 10:26:40

标签: c++ constructor 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)进行诅咒。如何初始化数组?随着变量一切顺利,一切都很好。感谢。

2 个答案:

答案 0 :(得分:5)

你的代码具有双重功能:除了在构造函数体内复制外,它还会复制到初始化列表中。

您不必这样做:保留可由列表中的初始化列表复制的项目,并将其从正文中删除;从初始化列表中删除其他项目:

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则使用正文中的循环进行初始化。

答案 1 :(得分:2)

由于原始数组不能以这种方式复制,因此请改用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;
}