C++写矩阵类

本文详细介绍了如何在C++中设计并实现一个矩阵类,包括构造、赋值、加减乘运算以及矩阵转置等功能。通过实例展示了类的使用方法,帮助读者深入理解C++的面向对象编程技巧。
摘要由CSDN通过智能技术生成
matrix.h
#pragma once
#ifndef __MATRIX_BASE__
#define __MATRIX_BASE__

#include <iostream>
#include <vector>
using namespace std;

class Matrix {

public:
	Matrix() {};
	Matrix(int row, int col);
	Matrix(const Matrix &A);
	~Matrix() {};

	void print(int row);
	void init(){
		array.resize(_row);
		array[0].resize(_col);

	}

	//运算符重载
	Matrix& operator + (const Matrix& rhs);
	Matrix& operator = (const Matrix& rhs);


	void add_row_element(int nrow, vector<double> vec);
private:
	int _row;
	int _col;
	vector<vector<double>> array;
};


#endif // !__MATRIX_BASE__


matrix.cpp



Matrix::Matrix(int row, int col)
{
	if (row < 0 || col < 0){
		cout << "Row or col must b
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
假设你已经定义了一个矩阵Matrix,可以按照以下步骤实现矩阵相加的功能: 1. 定义一个重载运算符+的函数,实现矩阵的相加操作。函数原型为: ```c++ Matrix operator+(const Matrix& mat) const; ``` 其中,const Matrix& mat表示传入的参数是一个矩阵,const表示这个参数是只读的,不会修改原有的矩阵,而const修饰的*this则表示当前对象也是只读的,不会被修改。返回值是一个新的矩阵,存储着两个矩阵相加的结果。 2. 在函数体内,首先判断两个矩阵是否具有相同的行列数,如果不同,抛出异常或者返回一个空矩阵。 3. 创建一个新的矩阵对象,存储相加的结果。 4. 使用两个for循环遍历两个矩阵的每个元素,将相应的元素相加,并存储到新矩阵的对应位置上。 5. 返回新矩阵对象。 下面是一个示例代码: ```c++ class Matrix { public: Matrix(int r, int c): rows(r), cols(c), data(new double[r*c]) {} Matrix(const Matrix& mat): rows(mat.rows), cols(mat.cols), data(new double[rows*cols]) { memcpy(data, mat.data, rows*cols*sizeof(double)); } ~Matrix() { delete[] data; } Matrix operator+(const Matrix& mat) const { if (rows != mat.rows || cols != mat.cols) { // 抛出异常或者返回一个空矩阵 throw std::invalid_argument("Matrix dimensions don't match."); } Matrix res(rows, cols); for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { res(i, j) = (*this)(i, j) + mat(i, j); } } return res; } double& operator()(int r, int c) { return data[r*cols+c]; } const double& operator()(int r, int c) const { return data[r*cols+c]; } private: int rows, cols; double* data; }; ``` 使用示例: ```c++ int main() { Matrix A(3, 3); Matrix B(3, 3); // 初始化A和B,省略代码 Matrix C = A + B; return 0; } ``` 上述代码中,Matrix的构造函数、拷贝构造函数和operator()运算符重载函数都需要根据实际情况进行实现。在实际使用中,还需要考虑异常处理、内存管理等问题。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值