C++实现Cmatrix类

一、实验内容

CMatrix(): 不带参数的构造函数;
CMatrix(int nRow, int nCol, double *pData=NULL) : 带行、列及数据指针等参数的构造函数,并且参数带默认值;
CMatrix(const char * strPath): 带文件路径参数的构造函数;
CMatrix(const CMatrix& m): 拷贝构造函数
此外会用列表初始化成员变量:CMatrix(): m_nRow(0), m_nCol(0), m_pData(NULL);
bool Create(int nRow, int nCol, double *pData=NULL): 先删除原有空间,根据传入行列创建空间,如果pData不为空要将pData的内容拷贝到m_pData中。
二、析构函数
~CMatrix(): 调用Release();
Release(): 将内存释放,并将行列设置为0;
三、运算符重载
算术运算符重载:+, -, +=, -=
关系运算符重载:>, <, ==
下标操作符:[], ()
强制类型转换: double
赋值运算符:=,尤其注意当m1=m1特殊情况的处理
四、友元函数
输入和输出运输符:<<, >>

二、代码实现

 

        1.main.cpp

`        

#include 
#include 
#include "CMatrix.h"using namespace std;int main(int argc, char** argv) {double pData[10]={2,3,4,5};CMatrix m1,m2(2,5,pData), m3("d:\\1.txt"),m4(m2);cin>>m1;m2.Set(1,3,10);cout<#include CMatrix::CMatrix() : m_nRow(0), m_nCol(0), m_pData(0){}CMatrix::CMatrix(int nRow, int nCol, double* pData) : m_pData(0){Create(nRow, nCol, pData);}CMatrix::CMatrix(const CMatrix & m) : m_pData(0){*this = m;}CMatrix::CMatrix(const char* strPath){m_pData = 0;m_nRow = m_nCol = 0;ifstream cin(strPath);cin >> *this;}CMatrix::~CMatrix(){Release();}bool CMatrix::Create(int nRow, int nCol, double* pData){Release();m_pData = new double[nRow * nCol];m_nRow = nRow;m_nCol = nCol;if (pData){memcpy(m_pData, pData, nRow * nCol * sizeof(double));}}void CMatrix::Release(){if (m_pData){delete[]m_pData;m_pData = NULL;}m_nRow = m_nCol = 0;}CMatrix & CMatrix::operator=(const CMatrix & m){if (this != &m) {Create(m.m_nRow, m.m_nCol, m.m_pData);}return *this;}CMatrix & CMatrix::operator+=(const CMatrix & m){assert(m_nRow == m.m_nRow && m_nCol == m.m_nCol);for (int i = 0; i < m_nRow * m_nCol; i++){m_pData[i] += m.m_pData[i];}return *this;}//CMatrix& CMatrix::operator+(const CMatrix& m)//{//  assert(m_nRow==m.m_nRow && m_nCol==m.m_nCol);//  for(int i=0;i>(istream& is, CMatrix& m){is >> m.m_nRow >> m.m_nCol;m.Create(m.m_nRow, m.m_nCol);for (int i = 0; i < m.m_nRow * m.m_nCol; i++){is >> m.m_pData[i];}return is;}ostream & operator<<(ostream & os, const CMatrix & m){os << m.m_nRow << " " << m.m_nCol << endl;double* pData = m.m_pData;for (int i = 0; i < m.m_nRow; i++){for (int j = 0; j < m.m_nCol; j++){os << *pData++ << " ";}os << endl;}return os;
}

三、 实现结果

 1.txt内容

 运行截图

 

 


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部