2017-10-07 146 views
2

数组我有一个类无法初始化拷贝构造函数

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

由于原材料阵列的复制,这样一来,使用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; 
} 
+0

std :: array 行中的错误;未完成类型 – Xom9ik

+0

使用'#include '并确保'TRow'在使用之前进行竞争性声明。 – user0042

+0

谢谢。这就是我需要的 – Xom9ik

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与体内循环初始化英寸