#include <stdio.h>
#include <string.h>
class Matrix
{
double m_Data[16];
double* m_pRowhead[4];
public:
Matrix()
{
memset(m_Data, 0, 16*sizeof(double));
for(int i = 0; i < 4; i++)
m_pRowhead[i] = m_Data + i*4;
}
Matrix(const double* pArr)
{
CopyFrom(pArr);
for(int i = 0; i < 4; i++)
m_pRowhead[i] = m_Data + i*4;
}
Matrix(const Matrix& mat)
{
CopyFrom(mat.m_Data);
for(int i = 0; i < 4; i++)
m_pRowhead[i] = m_Data + i*4;
}
void CopyFrom(const double* pArr)
{
memcpy_s(m_Data, 16*sizeof(double), pArr, 16*sizeof(double));
}
double* operator[] (int nRowIndex)
{
return m_pRowhead[nRowIndex];
}
const double* operator[] (int nRowIndex) const
{
return m_pRowhead[nRowIndex];
}
double GetDiagonalSum(bool bMainDiagonal = true) const
{
double sum = 0.0;
int i;
if(bMainDiagonal)
{
for(i = 0; i < 4; i++)
sum += m_pRowhead[i][i];
}
else
{
for(i = 0; i < 4; i++)
sum += m_pRowhead[i][3-i];
}
return sum;
}
void PrintMatrix() const
{
for(int i = 0; i < 4; i++)
{
for(int j = 0; j < 4; j++)
printf_s("%.2lf\t", m_pRowhead[i][j]);
printf_s("\n");
}
}
};
void main()
{
double a[16] = {1.0, 2.0, 3.0, 4.0,
5.0, 6.0, 7.0, 8.0,
9.0, 8.0, 7.0, 6.0,
5.0, 4.0, 3.0, 2.0};
Matrix mat(a);
mat[0][0] = 2.5;
printf_s("主对角线之和为:%.4lf\n", mat.GetDiagonalSum());
printf_s("副对角线之和为:%.4lf\n", mat.GetDiagonalSum(false));
printf_s("打印矩阵:\n");
mat.PrintMatrix();
}
![](https://video.ask-data.xyz/img.php?b=https://iknow-pic.cdn.bcebos.com/6d81800a19d8bc3edfda0eee808ba61ea9d345c7?x-bce-process=image%2Fresize%2Cm_lfit%2Cw_600%2Ch_800%2Climit_1%2Fquality%2Cq_85%2Fformat%2Cf_auto)