c++重载:按元素添加矩阵的操作符+
C++ overloading: operator+ for adding Matrices by element
我试图重载一个矩阵程序的"+"运算符。这是我的代码,在我看来没问题。但是当我在主函数中添加两个矩阵时,什么都没有发生。有人能帮忙吗?谢谢:)
顺便说一句:
-程序编译和运行良好,直到它应该添加到矩阵。
-I假设在我的operator+()函数的实现中存在问题,因为我已经将代码复制到add(Mtrx,Mtrx)函数中进行测试,并且它也没有工作。
//Mtrx.h#ifndef MTRX_H_
#define MTRX_H_
#include <iostream>
#include <string>
using namespace std;
using std::ostream;
class Mtrx {
int lines,cols;
float **p;
public:
Mtrx();
Mtrx(int,int);
int getLines();
int getCols();
float getElement(int,int);
void setLines(int);
void setCols(int);
void setElement(int,int,float);
Mtrx operator+(Mtrx&);
~Mtrx();
};
ostream& operator<<(ostream& os, Mtrx& m);
#endif /* MTRX_H_ */
//Mtrx.cpp //...
//...
Mtrx::~Mtrx(){
delete p;
p = NULL;
}
Mtrx Mtrx::operator+(Mtrx& m){
if(this->getLines() == m.getLines() && this->getCols() == m.getCols()){
Mtrx res(getLines(),getCols());
for (int i = 1; i <= this->getLines(); i++){
for(int j = 1; j <= this->getCols(); j++){
res.setElement(i,j,(this->getElement(i,j)+m.getElement(i,j)));
}
}
return res;
}
您有析构函数,但缺少复制构造函数和赋值操作符。作为一个经验法则,如果你有其中的一个,你应该拥有所有的。
Mtrx(const Mtrx&);
Mtrx& operator=(const Mtrx&);
~Mtrx();
如果没有显式的复制构造函数,编译器将为您生成一个。但是它并不聪明,所以当它复制一个矩阵时,它不知道为p
分配新的内存。它只是复制指针,导致原始矩阵和副本都指向相同的内存。当它们的析构函数运行时,它们都将调用delete p
,这对第二个家伙来说是个坏消息。
这就是当operator+
返回并且复制res
时发生的情况。
检查括号。您可能缺少一个,或者您的if(false)的控制路径没有返回。
Mtrx Mtrx::operator+(Mtrx& m){
if(this->getLines() == m.getLines() && this->getCols() == m.getCols()){
Mtrx res(getLines(),getCols());
for (int i = 1; i <= this->getLines(); i++){
for(int j = 1; j <= this->getCols(); j++){
res.setElement(i,j,(this->getElement(i,j)+m.getElement(i,j)));
}
}
return res;
}
相关文章:
- 将成员变量添加到共享库中的类中,不会破坏二进制兼容性吗
- 如何在C++中从两个单独的for循环中添加两个数组
- POCO::PostgreSQL:如何将std::vector支持添加到`Binder::bind`
- 如何仅为一个函数添加延迟
- 如何防止 c++ 在从浮点型转换为双精度型(不适用于 IO)时添加额外的小数?
- 使用std::transform将一个范围的元素添加到另一个范围中
- 如何将更多文件夹添加到c++include路径
- 如何将元素添加到数组的线程安全函数?
- QT通过C++添加映射QML项目
- 如何将点击的信号和插槽添加到qt中的自定义按钮中
- 为什么添加两个字符串字面值不使用操作符+
- 将操作符重载添加到列表中
- 操作符重载c++在对象中添加int
- 使用自增操作符添加数组元素
- 为什么将操作符void*()转换函数添加到c++流类中
- 将std::cout添加到全局操作符新掩码SIGSEGV中
- 整数类和分数类的添加和比较数据的操作符重载
- 我可以添加自己的类型转换操作符,以便能够将c++对象转换为objective C吗?
- c++重载:按元素添加矩阵的操作符+
- 编译器添加引用操作符