面向对象程序设计实验-运算符重载

这篇实验旨在通过面向对象程序设计,实现运算符"<<"和">>"的重载,以及重载"+"以进行矩阵相加。在Windows平台上,使用Visual C++或Visual Studio作为集成开发环境,完成程序的编辑、编译、运行和调试。实验要求设计算法,使得重载后的运算符能有效应用于3x3矩阵的输入、输出和相加操作。
摘要由CSDN通过智能技术生成

一、实验目的及要求

  1. 了解在集成开发环境下程序的编辑、编译、连接、运行与调试;

二、实验设备与平台

  1. 实验设备:计算机;
  2. 平台:Windows 2000操作系统,Visual C++ 6.0或Microsoft Visual Studio 2005/2008/2010/2012/2013。

三、实验内容及步骤
1、重载运算符“<<”和“>>”的算法实现。

#include<iostream>
using namespace std;
class Point
{
    int x, y;
public:
    friend istream& operator >> (istream& in, Point& p);   
    friend ostream& operator << (ostream& out, Point& p);
};
istream& operator >> (istream& in, Point& p)
{
    cout << "x=";
    in >> p.x;
    cout << "y=";
    in >> p.y;
    return in;
}
ostream& operator << (ostream& out, Point& p)
{
    out << "x=" << p.x << "   y=" << p.y << endl;
    return out;
}

int main()
{
Point P;
cout << "请输入x, y的值:" << endl;
cin >> P;
cout << "输出x, y的值" << endl;
    cout << P;
}

2、编写程序,有两个均为3行3列的矩阵ml和m2,求两个矩阵之和。重载运算符“+”、“>>”和“<<”,使之能用于矩阵相加、输入和输出。

#include <iostream>
using namespace std;
class Matrix
{
public:
	Matrix(){}
	Matrix(const Matrix&);
	friend Matrix  operator+( Matrix& a, Matrix& b);
	friend ostream& operator<<(ostream& a, const Matrix& b);
	friend istream& operator>>(istream& a, Matrix& b);
private:
	double a[3][3];
};
Matrix::Matrix(const Matrix& b)
{
	for (int i = 0; i < 3; i++)
	{
		for (int j = 0; j < 3; j++)
		{
			a[i][j] = b.a[i][j];
		}
	}
}
Matrix  operator+( Matrix& a,  Matrix& b)
{
	Matrix p;
	for (int i = 0; i < 3; i++)
	{
		for (int j = 0; j < 3; j++)
		{
			p.a[i][j] = a.a[i][j] + b.a[i][j];
		}
	}
	return p;
}
ostream& operator<<(ostream& out,const Matrix& b)
{

	for (int i = 0; i < 3; i++)
	{
		for (int j = 0; j < 3; j++)
		{
			out << b.a[i][j]<<'\t';
		}
		cout << '\n';
	}
	return out;
}
istream& operator>>(istream& in, Matrix& b)
{
	for (int i = 0; i < 3; i++)
	{
		for (int j = 0; j < 3; j++)
		{
			in >> b.a[i][j];
		}
	}
	return in;
}
int main()
{
	Matrix a, b;
	cout << "请输入第一个矩阵的元素:\n";
	cin >> a;
	cout << "请输入第2个矩阵的元素:\n";
	cin >> b;
	cout << "两个矩阵相加的结果为:\n";
	cout << a + b;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值