#include <iostream.h>
class matrix
{
public :
matrix( int r = 2, int c = 2 );
matrix( matrix &m );
~matrix();
void set( void );
matrix operator =( matrix &m );
matrix operator +( matrix &m );
matrix operator -( matrix &m );
matrix operator *( matrix &m );
double operator ()( int x, int y );
matrix rev( void );
friend ostream & operator <<( ostream & out, matrix &m );
private :
int row;
int col;
double **p;
};
matrix::matrix( int r, int c )
{
int i;
row = r;
col = c;
p = new double *[row];
for ( i = 0; i < row; i++ )
*(p + i) = new double [col];
}
matrix::matrix( matrix &m )
{
int i, j;
row = m.row;
col = m.col;
p = new double *[row];
for ( i = 0; i < row; i++ )
*(p + i) = new double [col];
for ( i = 0; i < row; i++ )
for ( j = 0; j < col; j++ )
*(*(p + i) + j) = *(*(m.p + i) + j);
}
matrix::~matrix()
{
int i;
for ( i = 0; i < row; i++ )
delete []*(p + i);
delete []p;
}
void matrix::set( void )
{
int i, j;
cout << "??????????????:" << endl;
for ( i = 0; i < row; i++ )
for ( j = 0; j < col; j++ )
cin >> *(*(p + i) + j);
}
matrix matrix::operator =( matrix &m )
{
int i, j;
for ( i = 0; i < row; i++ )
for ( j = 0; j < col; j++ )
*(*(p + i) + j) = *(*(m.p + i) + j);
return (* this );
}
matrix matrix:: operator +( matrix &m )
{
int i, j;
matrix a( row, col );
if ( row != m.row || col != m.col )
throw 0;
for ( i = 0; i < row; i++ )
for ( j = 0; j < col; j++ )
*(*(a.p + i) + j) = *(*(p + i) + j) + *(*(m.p + i) + j);
return (a);
}
matrix matrix::operator -( matrix &m )
{
int i, j;
matrix a( row, col );
if ( row != m.row || col != m.col )
throw 0;
for ( i = 0; i < row; i++ )
for ( j = 0; j < col; j++ )
*(*(a.p + i) + j) = *(*(p + i) + j) - *(*(m.p + i) + j);
return (a);
}
matrix matrix::operator *( matrix &m )
{
if ( col != m.row )
throw 0;
int i, j, k;
double sum;
matrix a( row, m.col );
for ( i = 0; i < row; i++ )
for ( j = 0; j < m.col; j++ )
{
for ( k = 0, sum = 0; k < col; k++ )
sum = sum + *(*(p + i) + k) * *(*(m.p + k) + j);
*(*(a.p + i) + j) = sum;
}
return (a);
}
double matrix::operator ()( int x, int y )
{
if ( x > row || y > col )
throw 0.0;
return (*(*(p + x - 1) + y - 1) );
}
matrix matrix::rev( void )
{
int i, j;
matrix a( col, row );
for ( i = 0; i < row; i++ )
for ( j = 0; j < col; j++ )
*(*(a.p + j) + i) = *(*(p + i) + j);
return (a);
}
ostream & operator <<( ostream & out, matrix &m )
{
int i, j;
for ( i = 0; i < m.row; i++ )
{
for ( j = 0; j < m.col; j++ )
out << *(*(m.p + i) + j) << " " ;
out << endl;
}
return (out);
}
int main()
{
matrix a( 2, 3 ), b( 3, 2 );
a.set();
b = a.rev();
cout << "????a:" << endl;
cout << a;
cout << "????a??????b:" << endl;
cout << b;
return (0);
}
来源: http://tool.oschina.net/highlight
|