【发布时间】:2019-05-01 14:32:21
【问题描述】:
我有两个矩阵应该通过在构造函数类中重载 * 运算符来相乘,但这里的问题是没有 operator [] 匹配这些操作数。为什么?
我看了视频,问了我的同学多次,尝试了我自己的方法,但我无法做到。我只得到这个错误!
这是我遇到问题的代码:
构造函数代码:
我做了两种方法来使这段代码工作。结果应存储在单元矩阵或新矩阵中:
Matrix operator*(const Matrix &matrix1, const Matrix &matrix2)
{
if (matrix1.Cols != matrix2.Rows) {
throw("Error");
}
cell.resize(matrix2.Cols); // one way to call
Matrix res(matrix1.Rows, matrix2.Cols, 1.0); // second way to call
for (int i = 0; i < matrix1.Rows; i++) {
cell[i].resize(matrix1.Rows);
for (int j = 0; j < matrix2.Cols; j++) {
double value_of_elements;
for (int k = 0; k = matrix1.Cols; k++) {
res[i][j] += matrix1[i][k] * matrix2[i][j];//
1. metod
value_of_elements += matrix1[i][k] *
matrix2[i][j];// 2. metod
}
cell[i][j]+=value_of_elements;
}
}
return res;
}
标头代码:
除非需要进行一些修改,否则我通常没有标头代码。
friend Matrix operator*(const Matrix &matrix1, const Matrix &matrix2);
源代码:
这是测试代码的地方:
try {
Matrix m1(3, 3, 1.0);
Matrix m2(3, 4, 1.0);
std::cout << "m1*m2:" << m1 * m2 << std::endl;// this si where the matrix should be multiplied here;
}
catch (std::exception &e) {
std::cout << "Exception: " << e.what() << "!" << std::endl;
}
catch (...) {
std::cout << "Unknown exception caught!" << std::endl;
}
system("pause");
return 0;
}
结果:
结果应该是这样的:
m1*m2:[3, 3, 3, 3
3, 3, 3, 3
3, 3, 3, 3]
我得到的是一个错误;错误的原因是res[i][j]、matrix1[i][k] 等有操作符 [] 不能在这些操作数上工作:
Error C2065 'cell': undeclared identifier 71 matrix.cpp
Error C2065 'cell': undeclared identifier 74 matrix.cpp
Error C2065 'cell': undeclared identifier 81 matrix.cpp
Error C2088 '[': illegal for class 79 matrix.cpp
Error C2088 '[': illegal for class 78 matrix.cpp
Error C2676 binary '[': 'Matrix' does not define this operator or a conversion to a type acceptable to the predefined operator 78 matrix.cpp
Error C2676 binary '[': 'const Matrix' does not define this operator or a conversion to a type acceptable to the predefined operator 78 matrix.cpp
Error C2676 binary '[': 'const Matrix' does not define this operator or a conversion to a type acceptable to the predefined operator 79 matrix.cpp
Error (active) E0020 identifier "cell" is undefined 71 Matrix.cpp
Error (active) E0349 no operator "[]" matches these operands 78 Matrix.cpp
Error (active) E0349 no operator "[]" matches these operands 78 Matrix.cpp
Error (active) E0349 no operator "[]" matches these operands 78 Matrix.cpp
Error (active) E0349 no operator "[]" matches these operands 79 Matrix.cpp
Error (active) E0349 no operator "[]" matches these operands 79 Matrix.cpp
【问题讨论】:
-
显然,您的
Matrix类不提供operator[]。您觉得错误消息的哪一部分不清楚? -
类
Matrix是否有包含这些值的成员?例如,如果您有成员vector<vector<double>> cell,则可以使用res.cell[i][j]访问它。如果你写res[i][j],编译器期望找到一个在类Matrix本身中声明的运算符[]。 -
好的,我试试这个...
-
另外,该函数不是类的成员。如果
cell是对象res的一部分,则始终需要编写res.cell。 -
好吧知道它有效,但这是第二个问题,矩阵超出范围......
标签: c++ matrix operator-overloading matrix-multiplication