64,648
社区成员
发帖
与我相关
我的任务
分享
#include <iostream>
using namespace std;
class Matrix
{
private:
double* data;
int row;
int column;
public:
Matrix(int row, int column)
{
this->row = row;
this->column = column;
data = new double[row * column];//(double*)malloc(sizeof(double) * row * column);
}
double* get_data()
{
return data;
}
int get_row()
{
return row;
}
int get_column()
{
return column;
}
Matrix& ADD(Matrix& matrix)
{
if((row != matrix.get_row()) || (column != matrix.get_column()))
{
cout << "Fails to add two matrices with different row or column." << endl;
}
for(int i = 0; i < row; ++i)
{
for(int j = 0; j < column; ++j)
{
*(data + i * column + j) += *(matrix.get_data() + i * column + j);
}
}
return *this;
}
Matrix& MINUS(Matrix& matrix)
{
if((row != matrix.get_row()) || (column != matrix.get_column()))
{
cout << "Fails to minus a matrix with different row or column." << endl;
}
for(int i = 0; i < row; ++i)
{
for(int j = 0; j < column; ++j)
{
*(data + i * column + j) -= *(matrix.get_data() + i * column + j);
}
}
return *this;
}
void display()
{
for(int i = 0; i < row; ++i)
{
for(int j = 0; j < column; ++j)
{
cout << *(data + i * column + j) << "\t";
}
cout << endl;
}
}
~Matrix()
{
//free(data);
delete[] data;
}
};
int main(int argc, char** argv)
{
Matrix a(2, 2);
for(int i = 0; i < 2; ++i)
{
for(int j = 0; j < 2; ++j)
{
*(a.get_data() + i * 2 + j) = 1 + i * 2 + j;
}
}
a.display();
cout << "============" << endl;
Matrix b(2, 2);
for(int i = 0; i < 2; ++i)
{
for(int j = 0; j < 2; ++j)
{
*(b.get_data() + i * 2 + j) = 2 + i * 2 + j;
}
}
b.display();
cout << "============" << endl;
//a.ADD(b);
//a.display();
//cout << "============" << endl;
b.MINUS(a);
b.display();
return 0;
}