栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

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

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

效果如下
int main()
{
	vector> arraya = {{1,3,4,5},{5,6,7,3},{8,6,8,4}};
	Matrix a(3, 4);
	
	a = arraya;                //二维vector赋值给矩阵
	cout << a << endl;
	
	vector> 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> array);    //=运算符重载函数

private:

	void load()                    //初始化数据。生成对应行列元素都是0的矩阵
	{
		p = new double*[row];                        //让p指向 储存double指针的数组
		for(int i = 0; i 

+运算符重载 实现

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

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

Matrix &Matrix::operator = (vector> array)
{
	for(int i=0; i 

 <<运算符重载实现

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

ostream& operator << (ostream &out, Matrix &b)
{
	for(int i =0; i 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/923759.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号