简体   繁体   English

在 C++ 中添加矩阵

[英]Addition of Matrix in C++

The following code gives me the wrong output. actually, it is not doing sum, it actually copies the 2nd object to the M3 object instead of calculating the sum.下面的代码给了我错误的 output。实际上,它不是在求和,它实际上是将第 2 个 object 复制到 M3 object 而不是计算求和。 I think I have some logical errors in + operator overloading.我认为我在 + 运算符重载方面存在一些逻辑错误。 Does anybody have any idea or any other suggestion?有人有任何想法或任何其他建议吗? it displays the output actually which is called in the copy constructor function cout<data[r][c]<<"\t";.它显示在复制构造函数 function cout<data[r][c]<<"\t"; 中实际调用的 output。 but it did not display output when I use M3.displayData().但是当我使用 M3.displayData() 时它没有显示 output。 #include #包括

#include <string.h>
using namespace std;

class Matrix{
    private:
        int noOfRows;
        int noOfColumns;
        int **data;
    public:
        Matrix(int noOfRows, int noOfColumns);
        void displayData();
        ~Matrix();
        Matrix (const Matrix &ref);
        Matrix operator + (Matrix m);
        Matrix& operator=(Matrix m) { 
        std::swap(m.noOfRows, noOfRows); 
        std::swap(m.noOfColumns, noOfColumns); 
        std::swap(m.data, data); 
        return *this; }
};

Matrix::Matrix(int inr=0, int inc=0){
    noOfRows=inr; noOfColumns=inc;
    data=new int*[noOfColumns];
    for(int i=0;i<noOfRows;i++)
        data[i]=new int[noOfColumns];
    int d;
    for(int r=0;r<noOfRows;r++){
        for(int c=0;c<noOfColumns;c++){
            cout<<"Enter ...";cin>>d;
            data[r][c]=d;
        }
        cout<<endl;
    }
}

Matrix::Matrix (const Matrix &ref){
    this->data=new int*[ref.noOfColumns];
    for(int i=0;i<ref.noOfRows;i++)
        this->data[i]=new int[ref.noOfRows];
    
    for(int r=0;r<ref.noOfRows;r++){
        for(int c=0;c<ref.noOfColumns;c++){
            this->data[r][c]=ref.data[r][c];
            cout<<this->data[r][c]<<"\t";
        }
        cout<<endl;
    }
}

Matrix Matrix::operator + (Matrix m){
    Matrix ms(m.noOfRows,m.noOfColumns);
    ms=0;
    for (int i=0; i<m.noOfRows; i++) 
        for (int j=0; j<m.noOfColumns; j++){
        ms.data[i][j] = data[i][j]+m.data[i][j];
        return ms;
        } 
    }

void Matrix::displayData(){
    for(int r=0;r<noOfRows;r++){
        for(int c=0;c<noOfColumns;c++)
            cout<<data[r][c]<<"\t";
        cout<<endl;
    }
}

Matrix::~Matrix(){
    delete[] data;
}

int main(){
    Matrix M1(2,2),M2(2,2);
    cout<<"\n Matrix A="<<endl;
    M1.displayData();
    cout<<"\n Matrix B="<<endl;
    M2.displayData();
    cout<<"\n Sum of Matrix="<<endl;
    Matrix M3=M1+M2;
    M3.displayData();
    return 0;
}

程序输出在这里:

There are at least four issues with your code:您的代码至少有四个问题:

  1. The Matrix copy constructor fails to copy the noOfRows and noOfColumns values. Matrix复制构造函数无法复制noOfRowsnoOfColumns值。

  2. You erroneously allocated the row pointers by using noOfColumns as the number of rows.您使用noOfColumns作为行数错误地分配了行指针。

  3. In the Matrix operator + , you are returning the Matrix inside the for loop, when you should be returning it after the loop is completed.Matrix operator +中,您在for循环内返回Matrix ,而您应该在循环完成后返回它。

  4. Your destructor fails to delete[] all the row and column data.您的析构函数无法delete[]所有行和列数据。

To fix the first two issues, since there is a lot of common code between the Matrix default constructor and the copy constructor, you could create an Allocate member function to allocate the memory:要解决前两个问题,因为Matrix默认构造函数和复制构造函数之间有很多公共代码,您可以创建一个Allocate成员 function 来分配 memory:

class Matrix
{
    private:
       void Allocate();
    //... other members
    public:
        Matrix operator + (const Matrix& m);
    // other members...
};

Matrix::Matrix(int inr=0, int inc=0) : noOfRows(inr), noOfColumns(inc)
{
    Allocate();
    // Input code removed...
}

Matrix::Matrix (const Matrix &ref) : noOfRows(ref.noOfRows), noOfColumns(ref.noOfColumns)
{
    Allocate();
    for(int r=0; r < ref.noOfRows; r++)
    {
        for(int c=0; c < ref.noOfColumns; c++)
            data[r][c] = ref.data[r][c];
    }
}

void Matrix::Allocate()
{
    data=new int*[noOfRows];
    for(int i=0;i < noOfRows; i++)
        data[i]=new int[noOfColumns]();
}

For operator + , you should pass the Matrix by const reference, not by value (this is in addition to fixing the mistake of returning the Matrix prematurely):对于operator + ,您应该通过 const 引用而不是值传递Matrix (这是为了修复过早返回Matrix的错误):

Matrix Matrix::operator + (const Matrix& m)
{
    Matrix ms(m.noOfRows,m.noOfColumns);
    for (int i=0; i<m.noOfRows; i++) 
    { 
        for (int j=0; j<m.noOfColumns; j++)
            ms.data[i][j] = data[i][j]+m.data[i][j];
    }
    return ms;
}

The last issue (the destructor) only removes the row pointers, but does not remove the data allocated for each row.最后一个问题(析构函数)只移除行指针,但不会移除为每一行分配的数据。 The fix is below:修复如下:

Matrix::~Matrix()
{
    for (int i = 0; i < noOfRows; ++i)
        delete[] data[i];
    delete [] data;
}

Other issues:其他事宜:

  1. Put more space between operators.在运算符之间留出更多空间。 Your current code squishes everything together, making it hard to read.您当前的代码将所有内容压缩在一起,使其难以阅读。 For example:例如:

for(int c=0;c<ref.noOfColumns;c++) could be: for (int c=0; c < ref.noOfColumns; c++) for(int c=0;c<ref.noOfColumns;c++)可以是: for (int c=0; c < ref.noOfColumns; c++)

  1. Excessive and unnecessary usage of this-> .过度和不必要地使用this->

  2. If Matrix::operator + exists, it makes sense for Matrix::operator += to also exist.如果Matrix::operator +存在,那么Matrix::operator +=也存在是有意义的。 For the latter, operator + would simply be implemented in terms of operator += , making operator + one or two lines of code.对于后者, operator +将简单地根据operator +=来实现,使operator +一两行代码。

  3. A probably better method of allocating the memory is illustrated by this answer , since only two allocations are done, the memory allocated is contiguous, and less memory fragmentation will occur. 这个答案说明了一种可能更好的分配 memory 的方法,因为只完成了两次分配,分配的 memory 是连续的,并且会发生更少的 memory 碎片。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM