【发布时间】:2013-02-11 08:58:16
【问题描述】:
我正在尝试为 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;
}
【问题讨论】:
-
您对
1..nLines和1..nCols的迭代看起来很可疑。这是故意的还是你的意思是从零开始? -
你也可以粘贴你的 main() 吗? operator+ 看起来不错。
标签: c++ matrix operators operator-overloading addition