gpt4 book ai didi

c++ - 重载运算符时二进制表达式的无效操作数

转载 作者:行者123 更新时间:2023-11-28 00:08:19 25 4
gpt4 key购买 nike

我正在尝试编写一个 C++ 程序,它使用 mul 和 add 运算符重载实现一个简单的矩阵。我的矩阵存储在一个简单的 Vector 中。我还重载了 () 运算符,以便轻松地将值存储在我的矩阵中。

template < typename T1, int rows, int cols>  
class Matrix{
public:
int row = rows;
int line = cols;
vector<T1> local_matrix;
Matrix(){
local_matrix = vector<T1>(rows*cols, 0);
}
T1 &operator () (int i, int j){
return local_matrix.at(i * cols +j);
}
const Matrix<T1, rows, cols> operator* (const Matrix<T1, rows, cols> &other) const{
Matrix<T1, other.row, other.line> result; // store the result here
int sum_elements_i = 0;
int left_counter = 0; // counter to iterate over the left Matrix
int right_counter = 0; // and for the right one
for(int i = 0; i < rows -1;++i){
for(int j = 0; j < other.spalte -1; ++j){
sum_elements_i = 0;
for(int k = 0; k < other.reihe -1; ++k){
sum_elements_i += local_matrix.at(left_counter) * other.local_matrix.at(right_counter);
left_counter++; // get the next value of the left matrix
right_counter += other.line; // and the next one of the right here we need to skip n-elements
// so its the 1st/2nd/.. value of the next line
}
right_counter = j+1;
result(i, j) = sum_elements_i;
}
left_counter = i+1;
}
return result;
}
};

我对 * 运算符的问题是,每次我想将 4x3 矩阵与 3x3 矩阵相乘时,程序都会崩溃,并显示以下错误消息:

invalid operands to binary expression ('Matrix<int, 4, 3>' and 'Matrix<int, 3, 3>')
E = D*A;
~^~

这是我调用函数的代码:

Matrix<int, 3, 3> A; // Datatype, Rows, Columns 
A(0,0) = 1; A(0,1) = 2; A(0,2) = 3;
A(1,0) = 1; A(1,1) = 2; A(1,2) = 3;
A(2,0) = 1; A(2,1) = 2; A(2,2) = 3;

Matrix<int, 4, 3> D, E;
D(0,0) = 1; D(0,1) = 2; D(0,2) = 3;
D(1,0) = 4; D(1,1) = 5; D(1,2) = 6;
D(2,0) = 7; D(2,1) = 8; D(2,2) = 9;
D(3,0) = 7; D(3,1) = 8; D(3,2) = 9;

std::cout << std::endl << "D:\n" << D << std::endl;

E = D*A;

非常感谢任何帮助,谢谢。

最佳答案

您必须为 operator * 使用正确的矩阵大小:

template <typename T, std::size_t N, std::size_t K, std::size_t M>
Matrix<T, N, M> operator* (const Matrix<T, N, K>& lhs, const Matrix<T, K, M>& rhs);

关于c++ - 重载运算符时二进制表达式的无效操作数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34279437/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com