📄 matrix.cpp
字号:
#include<iostream.h>
#include<math.h>
#include<stdlib.h>
#include<iomanip.h>
#include"matrix.h"
// 带默认参数值的构造函数
// 构造一个row行col列的零矩阵
Matrix::Matrix(int row, int col)
{
this->row = row; this->col = col;
this->n = row * col; this->mtx = new double[n];
for(int i=0; i<n; i++)
this->mtx[i] = 0.0;
}
// 用一个数组初始化矩阵
Matrix::Matrix(int row, int col, double mtx[])
{
this->row = row; this->col = col;
this->n = row * col; this->mtx = new double[n];
for(int i=0; i<n; i++)
this->mtx[i] = mtx[i];
}
// 拷贝构造函数,因为成员变量含有动态空间,防止传递参数
// 等操作发生错误
Matrix::Matrix(const Matrix &obj)
{
this->row = obj.getRow();
this->col = obj.getCol();
this->n = obj.getN();
this->mtx = new double[n];
for(int i=0; i<n; i++)
this->mtx[i] = obj.getMtx()[i];
}
// 格式化输出矩阵所有元素
void Matrix::print()const
{
for(int i=0; i<this->row; i++){
for(int j=0; j<this->col; j++)
if(fabs(this->get(i,j)) <= 1.0e-10)
cout << setiosflags(ios::left) << setw(12) << 0.0 << ' ';
else
cout << setiosflags(ios::left) << setw(12) << this->get(i,j) << ' ';
cout << endl;
}
}
// 获取矩阵元素
// 注意这里矩阵下标从(0,0)开始
double Matrix::get(const int i, const int j)const
{
return this->mtx[i*this->col + j];
}
// 修改矩阵元素
void Matrix::set(const int i, const int j, const double e)
{
this->mtx[i*this->col + j] = e;
}
// 重载赋值操作符,由于成员变量中含有动态分配
Matrix &Matrix::operator= (const Matrix &obj)
{
if(this == &obj) // 将一个矩阵赋给它自己时简单做返回即可
return *this;
delete[] this->mtx; // 首先删除目的操作数的动态空间
this->row = obj.getRow();
this->col = obj.getCol();
this->n = obj.getN();
this->mtx = new double[n]; // 重新分配空间保存obj的数组
for(int i=0; i<n; i++)
this->mtx[i] = obj.getMtx()[i];
return *this;
}
// 负号操作符,返回值为该矩阵的负矩阵,原矩阵不变
Matrix Matrix::operator- ()const
{
// 为了不改变原来的矩阵,此处从新构造一个矩阵
Matrix _A(this->row, this->col);
for(int i=0; i<_A.n; i++)
_A.mtx[i] = -(this->mtx[i]);
return _A;
}
// 矩阵求和,对应位置元素相加
Matrix operator+ (const Matrix &A, const Matrix &B)
{
Matrix AB(A.row, A.col);
if(A.row!=B.row || A.col!=B.col){
cout << "Can't do A+B\n"; // 如果矩阵A和B行列数不一致则不可相加
exit(0);
}
for(int i=0; i<AB.n; i++)
AB.mtx[i] = A.mtx[i] + B.mtx[i];
return AB;
}
// 矩阵减法,用加上一个负矩阵来实现
Matrix operator- (const Matrix &A, const Matrix &B)
{
return (A + (-B));
}
// 矩阵乘法
Matrix operator* (const Matrix &A, const Matrix &B)
{
if(A.col != B.row){ // A的列数必须和B的行数一致
cout << "Can't multiply\n";
exit(0);
}
Matrix AB(A.row, B.col); // AB用于保存乘积
for(int i=0; i<AB.row; i++)
for(int j=0; j<AB.col; j++)
for(int k=0; k<A.col; k++)
AB.set(i, j, AB.get(i,j) + A.get(i,k)*B.get(k,j));
return AB;
}
// 矩阵与实数相乘
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -