用C++写一个简易的矩阵运算类

前段时间做了一个机器人的仿真开发,需要用到矩阵运算,于是自己写了一套,分享出来。
easyMat.h:

class easyMat {
private:
	uint16_t row;
	uint16_t col;
	
public:
         float ** data;
	easyMat(uint16_t r, uint16_t c);
	easyMat(easyMat & e);           
	~easyMat() {                    
		for (auto i = 0; i < row; i++)
			delete[] data[i];
		delete[] data;
	}
	easyMat& operator= (float * d);
	void easyMat_Cout();
	friend easyMat& operator * (const easyMat Mat1, const easyMat Mat2); 
	friend easyMat& operator * (const easyMat Mat, const float k);
};

easyMat.cpp:

easyMat::easyMat(easyMat & e) {               //深拷贝构造函数函数
	row = e.row;
	col = e.col;
	data = new float*[row];
	for (auto i = 0; i < row; i++) {
		data[i] = new float[col];
	}

	for (auto i = 0; i < row; i++)
		for (auto j = 0; j < col; j++)
			data[i][j] = e.data[i][j];
}
easyMat::easyMat(uint16_t r, uint16_t c) :row(r), col(c) {  //构造函数,初始化一个二维指针数组
	data = new float*[row];
	for (auto i = 0; i < row; i++)
		data[i] = new float[col];
}
void easyMat::easyMat_Cout() {                              //将对象的数组打印
	for (auto i = 0; i < row; i++)
		for (auto j = 0; j < col; j++)
			std::cout << data[i][j] << std::endl;
}
easyMat& easyMat::operator = (float *d) {                   //重载"=",实现数组直接初始化data指针
	for (int i = 0; i < this->row; i++) {
		for(int j = 0;j < this->col; j++)
		     data[i][j] = d[i*this->col+j];
	}
	return *this;
}
easyMat& operator * (const easyMat Mat1, const easyMat Mat2) {  //两矩阵相乘
	easyMat * outMat = new easyMat(Mat1.row, Mat2.col);    
	for (auto i = 0; i < Mat1.row; i++) {
		for (auto j = 0; j < Mat2.col; j++) {
			outMat->data[i][j] = 0;
			for (auto m = 0; m < Mat1.col; m++)
				outMat->data[i][j] += Mat1.data[i][m] * Mat2.data[m][j];
		}
	}
	return *outMat;
}  
easyMat& operator* (const easyMat Mat, const float k) {         //矩阵与常数相乘
	easyMat * outMat = new easyMat(Mat.row, Mat.col); 
	for (auto i = 0; i < Mat.row; i++)
		for (auto j = 0; j < Mat.col; j++)
			outMat->data[i][j] = Mat.data[i][j] * k;
	return *outMat;
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值