c++重载:按元素添加矩阵的操作符+

C++ overloading: operator+ for adding Matrices by element

本文关键字:操作符 添加 重载 元素 c++      更新时间:2023-10-16

我试图重载一个矩阵程序的"+"运算符。这是我的代码,在我看来没问题。但是当我在主函数中添加两个矩阵时,什么都没有发生。有人能帮忙吗?谢谢:)

顺便说一句:

-程序编译和运行良好,直到它应该添加到矩阵。

-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;
}