Usually, I tend to use explicit
keyword in the constructor to avoid implicit conversion.
But when I try implement Matrix
class, compile error happened in the operator*()
function, it showed:
error: no matching constructor for initialization of 'Matrix'
, however, when I remove the explicit
key word in the copy constructor, every thing goes well.
I know what explicit
means, it means the parameter should be EXACTLY matched, when returning res
in the operator*()
function, the copy constructor will be called, I think the parameter is well matched, but why the error happened?
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!
}
};