【问题标题】:C++ overloading: operator+ for adding Matrices by elementC++ 重载:operator+ 用于按元素添加矩阵
【发布时间】: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


【解决方案1】:

检查你的牙套。您要么缺少一个,要么您的 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;
}

【讨论】:

    【解决方案2】:

    您有一个析构函数,但缺少一个复制构造函数和一个赋值运算符。根据经验,如果您拥有其中任何一个,您应该拥有所有这些。

    Mtrx(const Mtrx&);
    Mtrx& operator=(const Mtrx&);
    ~Mtrx();
    

    如果没有显式的复制构造函数,编译器将为您生成一个。但是,它并不聪明,因此它在复制矩阵时不知道为p 分配新内存。它只是复制指针,导致原始矩阵和副本都引用相同的内存。当他们的析构函数运行时,他们俩都会调用delete p,这对第二个人来说是个坏消息。

    这正是operator+ 返回并复制res 时发生的情况。

    【讨论】:

    • 谢谢,这似乎是问题所在。我是 C++ 初学者,所以我很难实现三法则。几个小时后,我确定我的新赋值运算符和析构函数正在工作,但我的复制构造函数仍然没有。 :(Mtrx::Mtrx(const Mtrx&amp; m){ cout&lt;&lt;"Copy Constructor called!"&lt;&lt;endl; lines = m.lines; cols = m.cols; p = new float*[lines]; for(int i = 0; i &lt; m.lines; i++){ for(int j = 0; j &lt; m.cols; j++){ cout&lt;&lt;"Copy constructor reached this point."&lt;&lt; endl; p[i][j] = m.p[i][j]; //dsnt reach here. } } }
    • 抱歉格式问题,我在这方面比在 C++ 方面更差。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多