gpt4 book ai didi

c++ - 重载运算符 : Matrix Addition

转载 作者:行者123 更新时间:2023-11-28 05:14:25 30 4
gpt4 key购买 nike

enter image description here

我正在尝试设置我的函数并执行一些重载操作,以便我可以 +、-、==、* 两个矩阵。我在第一次操作重载时遇到了一个问题:加法。

我的程序一直有效,直到我尝试添加 2 个矩阵。

感谢您的帮助。

include<iostream>
using namespace std;

class matrixType
{
private:
int rows,cols;
int** matrix;
public:

matrixType( int r, int c)
{
rows=r;
cols=c;
matrix = new int*[rows];
for(int i = 0; i < rows; ++i)
matrix[i] = new int[cols];
}

~matrixType()
{
for(int i = 0; i < rows; ++i)
{
delete [] matrix[i];
}
delete [] matrix;
}

matrixType operator+( matrixType m2 )
{
if( rows==m2.rows && cols==m2.cols)
{
matrixType m3(rows, cols);
for( int i=0; i<rows; i++)
{
for( int j=0; j<cols; j++)
{
m3.matrix[i][j]=matrix[i][j]+m2.matrix[i][j];
}
}
return m3;
}
}

matrixType operator-(matrixType m2)
{
if( rows==m2.rows && cols==m2.cols)
{
matrixType m3(rows, cols);
for( int i=0; i<rows; i++)
{
for( int j=0; j<cols; j++)
{
m3.matrix[i][j]=matrix[i][j]-m2.matrix[i][j];
}
}
return m3;
}
}

friend istream& operator>> (istream& stream, matrixType m)
{
for ( int i=0; i<m.rows;i++)
{
for( int j=0; j<m.cols;j++)
{
cout<<"Matrix"<<"["<<i<<"]"<<"["<<j<<"]"<<"=";
stream>>m.matrix[i][j];
cout<<endl;
}
}
return stream;
}

friend ostream& operator<<(ostream& out, matrixType m)
{
for ( int i=0; i<m.rows;i++)
{
for( int j=0; j<m.cols;j++)
{
cout<<"Matrix"<<"["<<i<<"]"<<"["<<j<<"]"<<"=";
out<<m.matrix[i][j];
cout<<endl;
}
}
return out;
}
};

最佳答案

作为替代方案的完全不同的方法 - 基于模板:

template <size_t Rows, size_t Columns>
class Matrix
{
int matrix[Rows][Columns];

public:
void operator+=(Matrix<Rows, Columns> const& other)
{
for(size_t i = 0; i < Rows; ++i)
{
for(size_t j = 0; j < Columns; ++j)
{
matrix[i][j] += other.matrix[i][j];
}
}
}

Matrix<Rows, Columns>
operator+(Matrix<Rows, Columns> const& other) const
{
Matrix<Rows, Columns> result(*this);
result += other;
return result;
}

template<size_t C>
Matrix<Rows, C> operator*(Matrix<Columns, C> const& other) const
{
// just exemplary, actual implementation missing:
return Matrix<Rows, C>();
}

// rest of operators coming here
};

它可能符合您的需求,也可能不符合您的需求,但如果符合,您就可以免费获得三分法则。此外,系统会自动阻止您添加或乘以不合适尺寸的矩阵。

另一方面——好吧,好处总是伴随着一些成本……——你失去了灵 active 。想象一下,您想将任意矩阵放入一个 vector 中 - 那么您需要一个基类,并且必须使用(智能?)指针,添加或乘以任意矩阵需要强制转换,...​​...

不过,最大的缺点是您需要在编译时知道您的矩阵大小 - 如果您不知道,我们就出局了。

顺便说一下,加法/乘法——在你原来的实现中,如果矩阵大小不匹配,你不会返回任何东西!那么你应该返回某种哨兵,e。 G。一个 0x0 矩阵 - 或者可能甚至更好:抛出一些适当的异常。

关于c++ - 重载运算符 : Matrix Addition,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42951961/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com