c ++如何使用其他ctor的ctor?

时间:2013-01-16 02:46:01

标签: c++

  

可能重复:
  Calling another constructor when constructing an object with const members

我希望后者使用前者。我怎么能用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 个答案:

答案 0 :(得分: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;
    }
}

`