C++程序设计基础8:运算符重载

222 阅读1分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。

前言

本文为笔者大一《面向对象程序设计》课程章节实验报告,现将题目整理并分享,希望能够帮助正在学习C++的小伙伴!本文将学习到的编程技能包括:重载运算符

知识提纲

重载运算符

  • 用途:在同一个作用域内,声明几个功能类似但形式参数不同的同名函数
  • 说明:这些同名函数的形式参数(指参数的个数、类型或者顺序)必须不同
  • 重载决策: 当调用一个重载函数或重载运算符时,编译器根据参数进行匹配,选择最合适的重载函数或重载运算符的过程。
  • 实现:见下方示例

一、重载<<和>>运算符

  • 重载类Point的运算符“<<”和“>>”,并测试该运算符。
  • 代码
#include  <iostream>
Using namespace std;
class Point
{
  int x , y ;
public:
	Point(){};
//重载运算符">>"
    friend istream & operator >> (istream &in, Point &p) ; 
//重载运算符"<<" 
   friend ostream & operator << (ostream &out, Point &p) ;  
} ;
#include <iostream>
using namespace std;

class Point
{
	int x, y;
public:
	Point(int xx=0,int yy=0)
	{
		x = xx; 
		y == yy;
	};

	friend istream & operator>> (istream &in, Point &p);	//重载运算符">>"

	friend ostream & operator<< (ostream &out, Point &p);	//重载运算符"<<" 
};

istream & operator>> (istream &in, Point &p)
{
	in >> p.x >> p.y;
	return in;
}

ostream & operator<< (ostream &out, Point &p)
{
	out << "(" << p.x << ',' << p.y << ")";
	return out;
}

int main()
{
	Point p;
	cout << "请输入一个点的坐标:(x,y) ";
	cin >> p;
	cout << "坐标:"<<p;
}

  • 结果 在这里插入图片描述

二、重载Matrix类的运算符

  • 题目:有两个均为3行3列的矩阵ml和m2,编写程序实现矩阵类Matrix,并重载运算符“+”、“>>”和“<<”,使之能用于矩阵m1和m2相加、输入和输出。
  • 代码
#include <iostream>
using namespace std;

class Matrix
{
public:
	friend istream&operator>>(istream&input, Matrix&p);
	friend ostream&operator<<(ostream&output, Matrix&p);
	Matrix& operator+(Matrix&A);
private:
	double elment[3][3];
};

istream&operator>>(istream&input, Matrix&p)
{
	cout << "请输入三阶矩阵:\n";
	for (int i= 0; i < 3; ++i)
	{
		for (int t = 0; t < 3; ++t)
		{
			input>>p.elment[i][t];
		}
	}
	return input;
}

ostream&operator<<(ostream&output, Matrix&p)
{
	output << "两个矩阵之和为:\n";
	for (int i = 0; i < 3; ++i)
	{
		for (int t = 0; t < 3; ++t)
		{
			output << p.elment[i][t];
			if (t != 2)
			{
				output << "  ";
			}
		}
		cout << endl;
	}
	return output;
}

Matrix& Matrix::operator+(Matrix&A)
{
	for (int i = 0; i < 3; ++i)
	{
		for (int t = 0; t < 3; ++t)
		{
			this->elment[i][t] = this->elment[i][t] + A.elment[i][t];
		}
	}
	return *this;
}

int main()
{
	Matrix A, B;
	cin >> A >> B;
	cout << A + B;
}

  • 结果 在这里插入图片描述