2017-10-07 64 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與體內循環初始化英寸