资源简介
C++矩阵计算类,可实现矩阵加减乘转置求逆等计算
代码片段和文件信息
#include “StdAfx.h“
#include “Matrix.h“
#include “math.h“
CMatrix::CMatrix(int rowint col)
{
iRow=row;
iCol=col;
dMatData = new double*[row];
for (int i=0; i < row; i++)
{
dMatData[i]= new double[col];
for(int j=0;j {
dMatData[i][j]=0;
}
}
}
// copy constructor,
//拷贝构造函数的作用:
//(1)以类对象作为函数参数传值调用时;
//(2)函数返回值为类对象;
//(3)用一个已定义的对象去初始化一个新对象时;
CMatrix::CMatrix (const CMatrix& m)
{
iRow=m.Row();
iCol=m.Col();
dMatData = new double*[iRow];
for (int i=0; i < iRow; i++)
{
dMatData[i]= new double[iCol];
for(int j=0;j {
memcpy(dMatData[i]m.dMatData[i]sizeof(double)*iCol);
}
}
}
CMatrix::~CMatrix(void)
{
for (int i=0; i < iRow; i++)
{
delete[] dMatData[i];
}
delete[] dMatData;
}
//返回数组元素(引用返回)
double& CMatrix::operator () (int row int col)
{
if (row >= iRow || col >= iCol)
{
throw( “CMatrix::operator(): Index out of range!“);
}
return dMatData[row][col];
}
////返回数组元素(重载)
double CMatrix::operator () (int row int col) const
{
if (row >= iRow || col >= iCol)
{
throw( “CMatrix::operator(): Index out of range!“);
}
return dMatData[row][col];
}
//重载预算符+
CMatrix operator + (const CMatrix& m1const CMatrix& m2)
{
if((m1.Col()!=m2.Col()) ||(m1.Row()!=m2.Row()) )
{
throw( “CMatrix::operator+: The two matrix have different size!“);
}
CMatrix matTmp(m1.Row()m1.Col());
for(int i=0;i {
for(int j=0;j {
matTmp(ij)=m1(ij)+m2(ij);
}
}
return matTmp;
}
//重载赋值运算符=,当左右两边矩阵的大小不相等时,
//以右边的大小为基准调整左边矩阵的大小
CMatrix &CMatrix::operator = (const CMatrix& m)
{
//revised in 2011-4-1 by Daiwujiao
// if(iRow!=m.Row()||iCol!=m.Col())
//{
// throw( “CMatrix::operator=: The two matrix have different size!“);
//}
if(iRow!=m.Row()||iCol!=m.Col())
{
SetSize(m.Row()m.Col());
}
for (int i=0; i < iRow; i++)
{
for(int j=0;j {
dMatData[i][j]=m(ij);
}
}
return *this;
}
//调整矩阵大小,原有值不变
void CMatrix::SetSize (int row int col)
{
if (row == iRow && col == iCol)
{
return;
}
double **rsData = new double*[row];
for (int i=0; i < row; i++)
{
rsData[i]= new double[col];
for(int j=0;j {
rsData[i][j]=0;
}
}
int minRow=(iRow>row)?row:iRow;
int minCol= (iCol>col)?col:iCol;
int colSize = minCol * sizeof(double);
for (int i=0; i < minRow; i++)
{
memcpy( rsData[i] dMatData[i] colSize);
}
for (int i=0; i < minRow; i++)
{
delete[] dMatData[i];
}
delete[] dMatData;
dMatData=rsData;
iRow=row;
iCol=col;
return;
}
//重载预算符-
CMatrix operator - (const CMatrix& m1const CMatrix& m2)
{
if((m1.Col()!=m2.Col()) ||(m1.Row()!=m2.Row()) )
{
throw( “CMatrix::operator-: The t
属性 大小 日期 时间 名称
----------- --------- ---------- ----- ----
目录 0 2018-01-19 13:30 Matrix\
文件 7449 2015-10-22 21:01 Matrix\Matrix.cpp
文件 1159 2015-10-15 21:56 Matrix\Matrix.h
评论
共有 条评论