[英]Overloading operator: Matrix Addition
我正在嘗試設置函數並執行一些重載操作,以便可以+,-,==,*兩個矩陣。 我在第一次操作重載時遇到了一個問題:加法。
我的程序可以正常工作,直到我嘗試添加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
};
它可能滿足或可能不滿足您的需求,但是如果滿足,您將免費獲得三個規則。 此外,系統會自動阻止您添加或相乘非適合大小的矩陣。
另一方面-好處總是也要付出一些代價...-您失去了靈活性。 想象一下,您想將任意矩陣放入向量中-您需要一個基類,然后必須使用(智能?)指針,對任意矩陣進行加或乘運算需要強制轉換,...
但是,最大的缺點是您需要在編譯時知道矩陣的大小-如果您不知道,我們就會淘汰。
順便說一句,加/乘-在原始實現中,如果矩陣大小不匹配,則不返回任何內容! 然后,您應該返回某種類型的哨兵,例如0x0矩陣-甚至可能更好:拋出一些適當的異常。
這聽起來像是違反三個規則的情況。
您需要實現一個復制構造函數:
matrixType(const matrixType&)
和一個副本分配運算符:
matrixType operator=(const matrixType&)
對於C++11
,最好實現move構造函數和move賦值運算符。
matrixType(matrixType&&)
matrixType& operator=(matrixType&& other)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.