重载*=矩阵c++的运算符
overload *= operator for matrices c++
我试图重载矩阵的*=运算符这是我为2个矩阵的*运算符所做的函数
template <class T>
Matrix<T> Matrix<T>::operator*(const Matrix& other) const
{
assert(cols == other.rows) ;
Matrix<T> temp(rows, other.cols) ;
for(unsigned i = 0 ; i < rows ; i++)
{
for(unsigned j = 0 ; j < other.cols ; j++)
{
temp.matrix[i][j] = 0 ;
for(unsigned k= 0 ; k < other.rows ; k++)
{
temp.matrix[i][j] = temp.matrix[i][j] + (matrix[i][k]*other.matrix[k][j]) ;
}
}
}
return temp ;
}
这是我的*=操作员实现
template <class T>
Matrix<T> Matrix<T>::operator*=(const Matrix& other) const
{
assert(cols == other.rows) ;
for(unsigned i = 0 ; i < rows ; i++)
{
for(unsigned j = 0 ; j < other.cols ; j++)
{
matrix[i][j] = 0 ;
for(unsigned k= 0 ; k < other.rows ; k++)
{
matrix[i][j] = matrix[i][j] + (matrix[i][k]*other.matrix[k][j]) ;
}
}
}
return *this ;
}
我不知道我的*=实现中的语义错误在哪里,因为它编译并运行,但输出远高于预期的
问题是,在对其中一个项求值时,不能将乘积的结果分配给它,因为这会破坏您仍然需要计算其他元素的原始值。
由于您有一个可工作的二进制*
,实现*=
的简单方法是将其作为*this = *this * other
。
可以有捷径,但需要矩阵具有特定的结构(对角线、三角形等)。在一般情况下,这是更简单、更安全的方法。
当然,我认为你们的矩阵至少是可复制和可赋值的。如果你也可以移动,你也可以获得性能。
您正在覆盖运算符的LHS,同时仍在尝试计算乘积。
以矩阵为例:
1 0
0 1
和
2 0
0 2
对于i = 0
和j = 0
,结束制作第一个矩阵;
0 0
0 1
在你开始乘法之前。你知道在那之后你不会得到正确的答案。
我不知道是否有一种技术可以用来将两个矩阵相乘,并将结果保存在LHS(或RHS)中。
相关文章:
- 为什么比较运算符如此快速
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- 使用C++中的模板和运算符重载执行矩阵运算
- 为什么这个运算符<重载函数对 STL 算法不可见?
- 增量运算符与后缀混淆
- 一个关于在C++中重载布尔运算符的问题
- 运算符C++ "delete []"仅删除 2 个前值
- 模板类无法识别友元运算符
- 我可以使用条件运算符初始化C风格的字符串文字吗
- 关闭||运算符优化
- 通过继承类使用来自不同命名空间的运算符
- C++Cast运算符过载
- 如何使用AngelScript注册SFML Vector2运算符
- 重载元组索引运算符-C++
- 如何使用重载的相等(==)运算符向测试用例添加描述
- 为什么Mat类的两个对象可以在不重载运算符+的情况下添加
- 多个If语句与使用逻辑运算符计算条件的单个语句的比较
- 布尔比较运算符是如何在C++中工作的
- 重载运算符new[]的行为取决于析构函数
- 如何防止clang格式在流运算符调用之间添加换行符<<