【发布时间】:2015-03-06 21:04:34
【问题描述】:
github repo with code
尝试通过重载某些操作来编写 Matrix 类。
当我试图用这个笔画编译时,一切都出错了
result = (l_mtx + r_mtx);
我从 g++ 收到错误:
g++ -g3 -std=c++11 -Wall -o 矩阵 matrix_class.h matrix.cpp
matrix.cpp:在函数“int main()”中:
matrix.cpp:36:12: error: no matching function for call to ‘Matrix::Matrix(Matrix)’
result = (l_mtx + r_mtx);
然后是这个函数的几个候选人,我不太明白。
我认为有复制构造函数和几个构造函数,但这不是我认为应该在该笔划中调用的 operator=。
matrix_class.h:73:5: 注意:Matrix::Matrix(Matrix&) [with type = double]
(没有已知的参数 1 从“Matrix”到“Matrix&”的转换
)
matrix_class.h:46:5: 注意:Matrix::Matrix(int, int) [with type = double]
(候选人期望 2 个参数,提供 1 个)
matrix_class.h:39:5: 注意:Matrix::Matrix() [with type = double]
(候选人期望 0 个参数,提供 1 个)
然后是错误:
matrix_class.h:96:18: 错误:初始化'Matrix Matrix::operator=(Matrix) [with type = double]'的参数1
我认为我没有正确编码分配运算符或复制构造函数,但我找不到错误在哪里。对不起愚蠢的问题。感谢关注。
//copy constructor
Matrix(const Matrix<type> &org)
{
cout << "Making a copy of " << this << endl;
row = org.getRow();
column = org.getColumn();
//allocate additional space for a copy
data = new type* [row];
for (int i = 0; i < row; ++i)
{
data[i] = new type [column];
}
for (int i = 0; i < row; ++i)
{
for (int j = 0; j < column; ++j)
{
data[i][j] = org.data[i][j];
}
}
}
和运算符=
//assign constructor
Matrix<type> operator = (Matrix<type> r_mtx)
{
if (row == r_mtx.getRow())
{
if (column == r_mtx.getColumn())
{
//TODO: удалить прежний объект?
Matrix<type> temp(row, column);
for (int i = 0; i < row; ++i)
{
for (int j = 0; j < column; ++j)
{
temp.data[i][j] = r_mtx[i][j];
}
}
return temp;
}
else
{
cout << "Assign error: matrix column are not equal!" << endl;
exit(EXIT_FAILURE);
}
}
else
{
cout << "Assign error: matrix rows are not equal!" << endl;
exit(EXIT_FAILURE);
}
}
【问题讨论】:
-
您的复制构造函数应该采用
const Matrix&。 -
您应该将代码的相关部分复制到您的问题中,而不是链接到外部网站。
-
@Brian 那么我将不允许更改它的字段
-
@Alexander 没错。这是一个副本。它根本不应该修改原件。
-
如果您有需要在复制时修改的字段,也许您应该声明它们
mutable?