#include二、运行结果#include #include "CMatrix.h" using namespace std; int main() { 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 1 3
1.txt 文件中为 2 2 1 2 3 4
结果为:
三、总结 1.构造函数 CMatrix();
CMatrix(int nRow, int nCol, double* pData=NULL);
CMatrix(const CMatrix& m);
CMatrix(const char* strPath);
- 构造函数,没有返回值也不写void
- 函数名称和类名相同
- 构造函数可以有参数,因此可以发生重载
- 程序在调用对象时候会自动调用构造,无须手动调用,并且只会调用一次
- 构造函数语法:类名(){}
~CMatrix();
- 析构函数,没有返回值也不写void
- 函数名称与类名相同,在名称前加上符号~
- 析构函数不可以有参数,因此不可以发生重载
- 程序在对象销毁前会自动调用析构,无须手动调用,并且只会调用一次
- 析构函数语法:~类名(){}
CMatrix & operator=(const CMatrix& m);
CMatrix & operator+=(const CMatrix& m);
double & operator[](int nIndex);
double& operator()(int nRow,int nCol);
bool operator==(const CMatrix& m);
bool operator!=(const CMatrix& m);
operator double();
- 算术运算符重载:+, -, +=, -=,
- 关系运算符重载:>, <, ==
- 下标操作符:[], ()
- 强制类型转换: double
- 赋值运算符:=,如果m1=m1,直接返回this;如果不是就先Create(m.m_nRow, m.m_nCol, m.m_pData),再返回this
- operator double()函数无需指明返回类型,double作为一个运算符,该函数用于double运算符重载
friend istream& operator>>(istream& is, CMatrix& m);//全局函数
friend ostream& operator<<(ostream& os, const CMatrix& m);
- 概念: 让一个函数或者类访问另一个类中私有成员,
- 特殊关键字:friend,
- 友元的三种实现:1)全局函数做友元。2)类做友元。3)成员函数做友元
- 本次实验中用了输入输出符号的重载作为友元函数。



