我正在尝试为 Matrix 程序重载“+”运算符。这是我的代码,我觉得没问题。但是当我在我的主函数中添加两个矩阵时,什么也没有发生。 有人可以帮忙吗? 谢谢:)
顺便说一句:
-程序编译并运行得很好,直到它应该添加到矩阵中。
-我假设我的 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
时发生的情况。
关于C++ 重载 : operator+ for adding Matrices by element,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15080135/