2013-01-16 18 views
0

Possible Duplicate:
Calling another constructor when constructing an object with const membersC++如何從另一個ctor使用ctor?

我希望後者使用前者。我怎麼能在C++中做到這一點?如果這是不可能的,爲什麼我不能讓*this = regMatrix作業?

RegMatrix::RegMatrix(int numRow,int numCol) 
{ 
    int i; 
    for(i=0;i<numRow;i++) 
    { 
     _matrix.push_back(vector<double>(numCol,0)); 
    } 
} 

RegMatrix::RegMatrix(const SparseMatrix &sparseMatrix) 
{ 
    RegMatrix regMatrix(sparseMatrix.getNumRow(),sparseMatrix.getNumCol()); 
    vector<Node> matrix = sparseMatrix.getMatrix(); 
    cout << "size: " << matrix.size() << endl; 
    for(std::vector<Node>::const_iterator it = matrix.begin(); it != matrix.end(); ++it) 
    { 
     cout << "Position: [" << (*it).i << ", " << (*it).j << "] Value:" << (*it).value << endl; 
     regMatrix._matrix[(*it).i][(*it).j] = (*it).value; 
    } 

    *this = regMatrix; 
} 

回答

1

您可以使用「Delegated Constructors」在新的C++ 0x中執行此操作。 `

RegMatrix(const SparseMatrix &sparseMatrix) : RegMatrix(sparseMatrix.getNumRow(),sparseMatrix.getNumCol()) 
{ 
    vector<Node> matrix = sparseMatrix.getMatrix(); 
    cout << "size: " << matrix.size() << endl; 
    for(std::vector<Node>::const_iterator it = matrix.begin(); it != matrix.end(); ++it) 
    { 
     cout << "Position: [" << (*it).i << ", " << (*it).j << "] Value:" << (*it).value << endl; 
     this->_matrix[(*it).i][(*it).j] = (*it).value; 
    } 
} 

`

+0

試圖做到這一點,把下面的代碼在頭文件,但我得到的語法錯誤:'(RegMatrix :: RegMatrix(常量稀疏矩陣和稀疏矩陣):RegMatrix(INT numRow行,INT numCol);)' – Tom

+0

刪除最後一個;)(固定在上面)。你使用什麼版本的C++編譯器。 – user1952500

+0

我改變了定義,但仍然得到語法錯誤:'RegMatrix(const SparseMatrix&sparseMatrix):RegMatrix(int numRow,int numCol);' – Tom