c++通过运算符重载,实现矩阵类简单输出、相加、赋值

效果如下

int main()
{
	vector<vector<int>> arraya = {{1,3,4,5},{5,6,7,3},{8,6,8,4}};
	Matrix a(3, 4);
	
	a = arraya;                //二维vector赋值给矩阵
	cout << a << endl;
	
	vector<vector<int>> arrayb = {{6,3,3,5},{5,2,1,3},{6,6,8,7}};
	Matrix b(3, 4);

	b = arrayb;
	cout << b << endl;
	
	b = b + a;
	cout << b << endl;
	
	return 0;
}

输出结果

 

实现

矩阵类的定义

class Matrix{
	friend ostream& operator << (ostream &out, Matrix &b);     //声明<<运算符重载友元
public:

	Matrix(int a, int b): row(a), column(b){      //构造函数,传入矩阵行和类,并调用load初始化
		load();
	};
	
	Matrix operator +(Matrix &b);                 //+运算符重载函数

	Matrix &operator = (vector<vector<int>> array);    //=运算符重载函数

private:

	void load()                    //初始化数据。生成对应行列元素都是0的矩阵
	{
		p = new double*[row];                        //让p指向 储存double指针的数组
		for(int i = 0; i<row; i++)
		{
			p[i] = new double[column];               //每个double指针再指向一个double数组
			for(int t = 0; t<column; t++)            //循环将每个元素赋值为0
				p[i][t] = 0;	
		}
	}
	double **p;                                //记录矩阵数据的地址
	int row;                                   //矩阵行数
	int column;                                //矩阵列数
};

+运算符重载 实现

Matrix Matrix::operator +(Matrix &b) 
{
	Matrix temp = *this;
	for(int i=0; i<row; i++)
		for(int t = 0; t<column; t++)
		{
			temp.p[i][t] = this->p[i][t] + b.p[i][t];
		}
	return temp;
}

=运算符重载实现,利用传入的vector<vector<int>>赋值

Matrix &Matrix::operator = (vector<vector<int>> array)
{
	for(int i=0; i<row; i++)
		for(int t=0; t<column; t++)
			p[i][t] = array[i][t];
			
	return *this;
}

 <<运算符重载实现

ostream类的拷贝构造函数和赋值函数是保护类型的,所以ostream不允许拷贝或者赋值,我们需要用两个引用来传入传出

ostream& operator << (ostream &out, Matrix &b)
{
	for(int i =0; i<b.row; i++)
	{
	 
		for(int t = 0; t<b.column; t++)
		{
			out << b.p[i][t] << " ";
		}
		out << endl; 
	}
	return out; 
	 
}

  • 2
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值