class Matrix //定义Matrix类
{
public:
Matrix(); //默认构造函数
friend Matrix operator+(Matrix &,Matrix &); //重载运算符“+”
friend Matrix operator-(Matrix &,Matrix &); //重载运算符“-”
void input(); //输入数据函数
void display(); //输出数据函数
private:
int mat[m][n];
};
Matrix::Matrix() //定义构造函数
{
for(int i = 0; i < n; i++)
for(int j = 0; j < m; j++)
mat[i][j] = 0;
}
Matrix operator+(Matrix &a,Matrix &b) //定义重载运算符“+”函数
{
Matrix c;
for(int i = 0; i < m; i++)
for(int j = 0;j < n;j++)
c.mat[i][j] = a.mat[i][j] + b.mat[i][j];
return c;
}
Matrix operator-(Matrix &a,Matrix &b) //定义重载运算符“-”函数
{
Matrix c;
for(int i = 0; i < m; i++)
for(int j = 0;j < n;j++)
c.mat[i][j] = a.mat[i][j] - b.mat[i][j];
return c;
}
void Matrix::input() //定义输入数据函数
{
cout << "input value of matrix:" << endl;
for(int i = 0; i < m; i++)
for(int j = 0; j < n; j++)
cin >> mat[i][j];
}
void Matrix::display() //定义输出数据函数
{
for (int i = 0; i < m; i++) {
for(int j = 0;j < n; j++) {
cout << mat[i][j] << " ";
}
cout << endl;
}
}
#include
#include
using namespace std;
class Matrix
{
private:
int m;
int n;
int *items;
public:
Matrix(int m, int n);
virtual ~Matrix();
int getValue(int i, int j) const;
void setValue(int i, int j, int v);
bool operator=(const Matrix& m1);
friend Matrix operator+(const Matrix& m1, const Matrix& m2);
//friend Matrix operator-(const Matrix &m1, const Matrix &m2);
void dump();
};
Matrix::Matrix(int m, int n)
{
assert(m > 0);
assert(n > 0);
this->m = m;
this->n = n;
this->items = new int[m*n];
for (int i = 0; i < m*n; i++)
{
this->items[i] = 0;
}
}
Matrix::~Matrix()
{
delete[] this->items;
this->items = NULL;
}
int Matrix::getValue(int i, int j) const
{
assert(i >= 0 && i < this->m);
assert(j >= 0 && j < this->n);
return this->items[this->m * i + j];
}
void Matrix::setValue(int i, int j, int v)
{
assert(i >= 0 && i < this->m);
assert(j >= 0 && j < this->n);
this->items[this->m * i + j] = v;
}
bool Matrix::operator=(const Matrix& m1)
{
assert(this->m == m1.m);
assert(this->n == m1.n);
for (int i = 0; i < this->m; i++)
{
for (int j = 0; j < this->n; j++)
{
this->items[this->m * i + j] = m1.items[this->m * i + j];
}
}
return true;
}
Matrix operator+(const Matrix& m1, const Matrix& m2)
{
assert(m1.m == m2.m);
assert(m1.n == m2.n);
Matrix result(m1.m, m1.n);
for (int i = 0; i < m1.m; i++)
{
for (int j = 0; j < m1.n; j++)
{
int r = m1.getValue(i, j) + m2.getValue(i, j);
result.setValue(i, j, r);
}
}
return result;
}
void Matrix::dump()
{
cout << "======= Matrix [" << this->m << " x " << this->n << "] =======\n";
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 2; j++)
{
cout << this->getValue(i, j) << ", ";
}
cout << "\n";
}
cout << endl;
}
int main()
{
Matrix m1(2, 2);
m1.setValue(0, 0, 1);
m1.setValue(0, 1, 2);
m1.setValue(1, 0, 3);
m1.setValue(1, 1, 4);
m1.dump();
Matrix m2(8, 2);
m2.setValue(0, 0, 5);
m2.setValue(0, 1, 6);
m2.setValue(1, 0, 7);
m2.setValue(1, 1, 8);
m2.dump();
Matrix m3(2, 2);
m3 = m1 + m2;
m3.dump();
return 0;
}