C++ 重载 : operator+ for adding Matrices by element

标签 c++ matrix operators operator-overloading addition

我正在尝试为 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/

相关文章:

python - "and"和 "or"如何处理非 bool 值?

c++ - C++:在程序中创建一个指针,然后在另一个程序中访问该位置

c++ - 为什么允许我从 const 成员函数调用 this->deviceContext->map()?

algorithm - 从不完整的联赛表中计算分数

r - 提取与 R 中其他列匹配的两个不同列中的值

java - 运算符作为 java 中的变量名称与 c 中的 #define 相同

c++ - 如何在 C++ 中初始化一个空的全局 vector

c++ 11用于多个项目的容器循环

arrays - 根据在另一个矩阵中的排序对矩阵进行排序

php - C 中是否有与 PHP 中相同的运算符 ===?