【发布时间】:2019-08-22 00:37:09
【问题描述】:
我想使用模板函数中另一个矩阵的转换来创建我的类 Matrix 的实例。
Matrix<T> m(A.tri_lo());
转换,这里tri_lo()返回一个新值,所以这里我的代码抛出一个错误:
error C2662: 'Matrix<long double> Matrix<long double>::tri_lo(bool)' : cannot convert a 'this' pointer from 'const Matrix<long double>' to 'Matrix<long double> &'
我尝试重载按值传递的构造函数,但我无法让它工作。这是我的构造函数:
Matrix() : data{ {T{}} } {}; // Implemented
Matrix(std::vector<std::vector<T>> _data) : data{ _data } {}; // Implemented
Matrix(unsigned int const lines, unsigned int const cols) { // Implemented
for (unsigned int i = 0; i < lines; i++) { this->data.push_back(std::vector<T>(cols, T())); }
};
template<class T2> Matrix(Matrix<T2> const& other) : data{ other.data } {}; // Implemented
template<class T2> Matrix(Matrix<T2> const other) : data{ other.data } {} // Implemented
我哪里出错了?
编辑:这是上下文。
template<class T>
template<class T2>
auto Matrix<T>::operator-(Matrix<T2> const& other) {
assert(this->lines() == other.lines());
assert(this->cols() == other.cols());
decltype(std::declval<T>() - std::declval<T2>()) T3;
Matrix<T3> res(this->lines(), this->cols());
for (unsigned int const i = 0; i < this->lines(); i++) {
for (unsigned int const j = 0; j < this->cols(); i++) {
res[i][j] -= other[i][j];
}
}
return res;
}
这里是full pastebin。如果需要,请随意包含一个小的代码审查!
【问题讨论】:
-
成员函数
tri_lo是否标记为const? -
你还没有给我们enough code to reproduce the problem,但我有可能
A是一个const变量而tri_lo是一个非常量函数? -
是的,A 在 const 变量中。
tri_lo声明如下:Matrix<T> tri_lo(bool include_diag = false);在类声明中。 -
@Magix 将 const 添加到其声明中:
Matrix<T> tri_lo(bool include_diag = false) const;或从A的声明中删除const -
我试过了,但我相信它并没有解决问题,尽管我可能需要在任何地方添加 const 才能真正检查。为什么添加
const会起作用?
标签: c++ constructor parameter-passing c++14 pass-by-reference