显式默认复制构造函数 - 编译错误

时间:2014-07-29 13:44:59

标签: c++

通常,我倾向于在构造函数中使用explicit关键字以避免隐式转换。

但是当我尝试实现Matrix类时,编译错误发生在operator*()函数中,它显示:

error: no matching constructor for initialization of 'Matrix'但是,当我删除复制构造函数中的explicit关键字时,一切顺利。

我知道explicit意味着什么,这意味着参数应该完全匹配,当在res函数中返回operator*()时,将调用复制构造函数,我认为参数是匹配良好,但为什么错误发生了?

class Matrix {
private:
  vector<vector<int>> mat;
  int n;

public:
  explicit Matrix(int n): n(n) {
    this->mat.assign(n, vector<int>(n, 0));
  }

  explicit Matrix(const Matrix& obj) {
    this->n = obj.mat[0].size();
    this->mat = obj.mat;
  }

  Matrix operator*(const Matrix& rhs) {
    Matrix res(n);

    for (int i = 0; i < n; ++i) {
      for (int j = 0; j < n; ++j) {
        for (int k = 0; k < n; ++k) {
          res.mat[i][j] += this->mat[i][k] * rhs.mat[k][j];
        }
      }
    }

    return res; // Compiler error here!
  }
};

0 个答案:

没有答案