一些运算符重载的例子

Zabbix在Ubuntu 22.04上的性能优化与监控实战:从基础安装到高级配置 本文详细介绍了在Ubuntu 22.04系统上部署和优化Zabbix监控系统的完整流程,从基础安装到高级配置。内容包括MySQL数据库设置、Zabbix服务器与Web前端优化、性能调优策略以及实战监控场景应用,帮助用户构建高效的企业级监控解决方案。 阅读详情

一些运算符重载的例子



DoubleSubscriptedArray类:重载函数调用运算符()

类的需求:
在这里插入图片描述
DoubleSubscriptedArray.h

#include <iostream>

class DoubleSubscriptedArray
{
	friend std::ostream& operator<<(std::ostream&, const DoubleSubscriptedArray&);
	friend std::istream& operator>>(std::istream&, DoubleSubscriptedArray&);
public:
	DoubleSubscriptedArray(int = 3, int = 3); // 默认构造函数,默认生成一个 3 * 5 的二维数组
	DoubleSubscriptedArray(const DoubleSubscriptedArray&); // 拷贝构造函数
	~DoubleSubscriptedArray(); // 析构函数
	int getSize() const // 返回该二维数组中的元素个数,row * column
	{
		return row * column;
	}
	int getRow() const // 返回行数
	{
		return row;
	}
	int getColumn() const // 返回列数
	{
		return column;
	}

	// 重载的运算符函数
	const DoubleSubscriptedArray& operator=(const DoubleSubscriptedArray&);
	bool operator==(const DoubleSubscriptedArray&) const;
	// 在类声明中直接定义重载的 != 运算符,使其成为内联函数,减少调用它的额外开销
	bool operator!=(const DoubleSubscriptedArray& right) const
	{
		return !((*this) == right);
	}
	// 两种访问二维数组元素的方法
	const int& operator()(int, int) const;
	int& operator()(int, int);
	// 因为二维数组本质上是由一个内置的一维数组实现,所以可以只使用一个参数来访问二维数组的指定元素
	const int& operator()(int) const;
	int& operator()(int);

private:
	// 该二维数组由一个一维数组实现
	size_t row;
	size_t column;
	int* ptr;
};

DoubleSubscriptedArray.cpp

#include <iostream>
#include <iomanip>
#include <stdexcept>
#include "DoubleSubscriptedArray.h"
using namespace std;

ostream& operator<<(ostream& output, const DoubleSubscriptedArray& array)
{
	for (size_t i = 0; i < (array.getRow() * array.getColumn()); i++)
	{
		output << setw(12) << array.ptr[i];

		if ((i + 1) % array.getColumn() == 0)
		{
			output << "\n";
		}
	}

	// 如果最后一行没有满,输出结束再输出一个新行
	if(array.getSize() % array.getColumn() != 0)
		output << endl;

	return output;
}

istream& operator>>(istream& input, DoubleSubscriptedArray& array)
{
	for (size_t i = 0; i < (array.getRow() * array.getColumn()); i++)
	{
		input >> array.ptr[i];
	}

	return input;
}

DoubleSubscriptedArray::DoubleSubscriptedArray(int rows, int columns)
	: row(rows > 0 ? rows :
		throw out_of_range("Array row must be greater than 0.")),
	column(columns > 0 ? columns :
		throw out_of_range("Array column must be greater than 0.")),
	ptr(new int[row * column])
{
	for (size_t i = 0; i < getSize(); i++)
	{
		ptr[i] = 0;
	}
}

DoubleSubscriptedArray::DoubleSubscriptedArray(const DoubleSubscriptedArray& array)
	: row(array.row),
	column(array.column),
	ptr(new int[row * column])
{
	for (size_t i = 0; i < getSize(); i++)
	{
		ptr[i] = array.ptr[i];
	}
}

DoubleSubscriptedArray::~DoubleSubscriptedArray()
{
	delete[] ptr;
}

const DoubleSubscriptedArray& DoubleSubscriptedArray::operator=(const DoubleSubscriptedArray& right)
{
	// 避免自我赋值
	if (this == &right)
	{
		return *this;
	}

	// 判断两个对象大小是否相同
	if (getSize() != right.getSize())
	{
		delete[] ptr;
		row = right.row;
		column = right.column;
		ptr = new int[getSize()];
	}

	for (size_t i = 0; i < getSize(); i++)
	{
		ptr[i] = right.ptr[i];
	}

	return *this;
}

bool DoubleSubscriptedArray::operator==(const DoubleSubscriptedArray& right) const 
{
	// 行或列有一个不相同则一定不同
	if (row != right.getRow() || column != right.getColumn())
	{
		return false;
	}

	// 行、列都相同,接着判断每个元素是否相同
	for (int i = 0; i < (row * column); i++)
	{
		if (ptr[i] != right.ptr[i])
		{
			return false;
		}
	}
	return true;
}

const int& DoubleSubscriptedArray::operator()(int rows, int columns) const
{
	// 判断参数是否越界
	// 参数从1开始
	if ((rows - 1) < 0 || (rows - 1) >= row)
	{
		throw out_of_range("row out of range.");
	}

	if ((columns - 1) < 0 || (columns - 1) >= column)
	{
		throw out_of_range("column out of range.");
	}

	return ptr[(rows - 1) * columns + (columns - 1)];
}

int& DoubleSubscriptedArray::operator()(int rows, int columns)
{
	// 判断参数是否越界
	// 参数从1开始
	if ((rows - 1) < 0 || (rows - 1) >= row)
	{
		throw out_of_range("row out of range.");
	}

	if ((columns - 1) < 0 || (columns - 1) >= column)
	{
		throw out_of_range("column out of range.");
	}

	return ptr[(rows - 1) * columns + (columns - 1)];
}

const int& DoubleSubscriptedArray::operator()(int n) const
{
	// 判断参数是否越界
	// 参数从1开始
	if (n < 0 || n >= getSize())
	{
		throw out_of_range("Subscript out of range.");
	}

	return ptr[n];
}

int& DoubleSubscriptedArray::operator()(int n)
{
	// 判断参数是否越界
	// 参数从1开始
	if (n < 0 || n >= getSize())
	{
		throw out_of_range("Subscript out of range.");
	}

	return ptr[n];
}

test.cpp

#include <iostream>
#include <stdexcept>
#include "DoubleSubscriptedArray.h"
using namespace std;

int main()
{
	DoubleSubscriptedArray integers1(3, 5);
	DoubleSubscriptedArray integers2;

	cout << "Size of Array integers1 is " << integers1.getSize()
		<< "\nrow is " << integers1.getRow() << ", column is " << integers1.getColumn()
		<< "\nArray after initialization:\n" << integers1 << endl;

	cout << "\nSize of Array integers2 is " << integers2.getSize()
		<< "\nrow is " << integers2.getRow() << ", column is " << integers2.getColumn()
		<< "\nArray after initialization:\n" << integers2 << endl;

	cout << "Enter 24 integers: " << endl;
	cin >> integers1 >> integers2;

	cout << "\nAfter input, the arrays contains:\n"
		<< "integers1:\n" << integers1
		<< "\nintegers2:\n" << integers2 << endl;

	cout << "\nEvaluation: integers1 != integers2." << endl;
	if (integers1 != integers2)
	{
		cout << "integers1 and integers2 are not equal." << endl;
	}

	// 调用拷贝构造函数,创建两个新对象
	DoubleSubscriptedArray integers3(integers1);
	DoubleSubscriptedArray integers4 = integers2; // 隐式调用拷贝构造函数,并不是使用重载的赋值运算符

	cout << "\nSize of Array integers3 is " << integers3.getSize()
		<< "\nrow is " << integers3.getRow() << ", column is " << integers3.getColumn()
		<< "\nArray after initialization:\n" << integers3 << endl;

	cout << "\nSize of Array integers4 is " << integers4.getSize()
		<< "\nrow is " << integers4.getRow() << ", column is " << integers4.getColumn()
		<< "\nArray after initialization:\n" << integers4 << endl;

	cout << "\nEvaluation: Assigning integers2 to integers1." << endl;
	integers1 = integers2;

	cout << "integers1:\n" << integers1
		<< "integers2:\n" << integers2 << endl;

	cout << "Evaluating: integers1 == integers2." << endl;
	if (integers1 == integers2)
	{
		cout << "integers1 and integers2 are equal." << endl;
	}

	// 测试重载的 () 运算符
	cout << "\nintegers1(5) is " << integers1(5) << endl;
	cout << "\nAssigning 1000 to integers1(5)" << endl;
	integers1(5) = 1000;
	cout << "integers1 is:\n" << integers1 << endl;
	cout << "\nAssigning 2000 to integers1(2, 2)" << endl; // 下标为5的元素处于第二行第二列
	integers1(2, 2) = 2000;
	cout << "integers1 is:\n" << integers1 << endl;

	// 测试该类的对象是否会自动检查边界
	try
	{
		cout << "Attempt to assigne 1000 to integers1[15]." << endl;
		integers1(15) = 1000;
	}
	catch (out_of_range& e)
	{
		cout << "An exception occured: " << e.what() << endl;
	}
}

运行结果:

在这里插入图片描述

上面代码中并没有重载双方括号运算符,因为它需要创建一个辅助类(管理单行,将一行看成一个一维数组来管理),在该辅助类中重载一个[]运算符,再在二维数组类中重载一个[]运算符,让它访问一行。由链式使用两个[]运算符来实现二维数组的访问,感兴趣的同学可以自己试着实现一下。

HugeInt类:大整数类

HugeInt.h

#include <iostream>
#include <array>
#include <string>

class HugeInt
{
	friend std::ostream& operator<<(std::ostream&, const HugeInt&);
public:
	static const int digits = 30; // HugeInt类对象的最大长度

	HugeInt(long = 0); // 默认构造函数,同时也是一个转换构造函数(long->HugeInt)
	HugeInt(const std::string&); // 转换构造函数,从string类对象转换成HugeInt

	// 重载加法运算符
	// 实现 HugeInt + HugeInt
	HugeInt operator+(const HugeInt&) const;
	// 实现 HugeInt + HugeInt
	HugeInt operator+(const int) const;
	// 实现 HugeInt + HugeInt
	HugeInt operator+(const std::string&) const;
private:
	std::array <short, digits> integer;
};

HugeInt.cpp

#include <cctype>
#include "HugeInt.h"
using namespace std;

ostream& operator<<(ostream& output, const HugeInt& num)
{
	int i = 0;
	// 跳过数组前面的0,最低位放在数组的最后一位
	for(i = 0; (i < HugeInt::digits) && (num.integer[i] == 0); i++)
		;
	
	// 如果此时i指向已经是数组的结尾
	if(i == HugeInt::digits)
		output << 0; // 此时该HugeInt对象的值为0
	else
	{
		for(; i < HugeInt::digits; i++)
			output << num.integer[i];
	}

	return output;
}

HugeInt::HugeInt(long value)
{
	// 将数组内容初始化为全0
	// 必须使用引用,才能修改数据成员array对象的值
	for(short& element : integer)
		element = 0;

	// 获取一个整型类型的数值的最低位是最方便的,%10和/10
	for (size_t i = digits - 1; value != 0 && i >= 0; i--)
	{
		integer[i] = value % 10;
		value /= 10;
	}
}

HugeInt::HugeInt(const string& number)
{
	for (short& element : integer)
		element = 0;

	// HugeInt对象的长度
	size_t length = number.size();

	// 获取一个string对象的第一个字符是最容易的
	for (size_t i = digits - length, j = 0; i < digits; i++, j++)
	{
		integer[i] = number.at(j) - '0'; // array对象中元素的类型为short,而字符在内存中保存的是ASCII编码的码值
		// 所以需要将其转换成对应的整型数值
	}
}

HugeInt HugeInt::operator+(const HugeInt& right) const
{
	HugeInt temp; // 保存计算结果
	int carry = 0; // 进位数

	// 从最低位开始计算
	for (int i = digits - 1; i >= 0; i--)
	{
		temp.integer[i] = integer[i] + right.integer[i] + carry;

		if (temp.integer[i] > 9)
		{
			temp.integer[i] %= 10;
			carry = 1;
		}
		else
		{
			carry = 0;
		}
	}

	return temp;
}

HugeInt HugeInt::operator+(int right) const
{
	return (*this) + HugeInt(right); // 使用转换构造函数将参数right转换成HugeInt类型对象
	// 再使用两个HugeInt对象的加法运算符进行计算
}

HugeInt HugeInt::operator+(const string& right) const
{
	// 同样使用转换构造函数将string对象转换成HugeInt对象,再进行计算
	return (*this) + HugeInt(right);
}

test.cpp

#include <iostream>
#include "HugeInt.h"
using namespace std;

int main()
{
	HugeInt n1(7654321); // 转换构造函数
	HugeInt n2(7891234); // 转换构造函数 long->HugeInt
	HugeInt n3("999999999999999999999999999"); // string->HugeInt
	HugeInt n4("1"); // string->HugeInt
	HugeInt n5; // 默认构造函数

	cout << "n1 is " << n1 << "\nn2 is " << n2
		<< "\nn3 is " << n3 << "\nn4 is " << n4
		<< "\nn5 is " << n5 << endl;

	n5 = n1 + n2; // HugeInt + HugeInt
	cout << "\n" << n1 << " + " << n2 << " = " << n5 << "\n\n";
	
	n5 = n3 + n4; // HugeInt + HugeInt
	cout << "\n" << n3 << " + " << n4 << " = \n" << n5 << "\n\n";

	n5 = n1 + 9; // HugeInt + int
	cout << n1 << " + " << 9 << " = " << n5 << "\n\n";

	n5 = n2 + "10000"; // HugeInt + string
	cout << n2 << " + " << "10000" << " = " << n5 << endl;
}

运行结果:

在这里插入图片描述

上面代码中只定义了HugeInt类中的加法操作,大家还可以参照上面的形式,补充其他运算。

VS配置RTKLIB(卫星定位开源代码)环境 @RTKlib代码调试教程-Visual Studio 2019 你好! 这是你第一次使用 Markdown编辑器 所展示的欢迎页。如果你想学习如何使用Markdown编辑器, 可以仔细阅读这篇文章,了解一下Markdown的基本语法知识。 ##RTKLIB-rtklib_2.4.3 提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档 @RTKlib代码调试教程-Visual Studio 2019 提示:这里可以添加本文要记录的大概内容: 例如:随着人工智能的不断发展,机器学习这门技 阅读详情

相关推荐

Zynq/ZynqMP PL端以太网实战:手把手教你用GMII to RGMII IP和EMIO打通网络(附KSZ9031 PHY驱动修改)

本文详细介绍了在Zynq/ZynqMP平台上使用GMII to RGMII IP核和EMIO接口实现PL端以太网通信的全栈开发流程,特别针对KSZ9031 PHY芯片提供了定制化驱动修改方案。内容涵盖硬件设计、Vivado配置、裸机驱动开发、Linux系统集成及实战调试技巧,帮助开发者高效解决工业控制和边缘计算中的以太网连接问题。

weixin_30642561的博客 582

运算符重载例子

#include "stdafx.h"#include "iostream.h"class A{public: operator A *() {  m=this;  return m; } A& operator*(){ m=this; return *m ;} A** operator&() { m=this; return &m ;} A* operator->(){ retu

文逗 1108

相衬成像介绍

相衬成像介绍

qq_41981768的博客 2911

运算符重载_例子

#include #include #include #include using namespace std; class Complex { public: Complex(){real=0,imag=0;} Complex(double r,double i){real=r;imag=i;} Complex operator+(Complex &c2); voi

时有限 676

DDR4协议规范之(一)DDR4结构和寻址

DDR4 SDRAM结构和寻址DDR4 SDRAM的封装和寻址新的改变功能快捷键合理的创建标题,有助于目录的生成如何改变文本的样式插入链接与图片如何插入一段漂亮的代码片生成一个适合你的列表创建一个表格设定内容居中、居左、居右SmartyPants创建一个自定义列表如何创建一个注脚注释也是必不可少的KaTeX数学公式新的甘特图功能,丰富你的文章UML 图表FLowchart流程图导出与导入导出导入 DDR4 SDRAM的封装和寻址 你好! 这是你第一次使用 Markdown编辑器 所展示的欢迎页。如果你想学习

YJFeiii的博客 3万+

USB摄像头开发实战:从参数配置到图像采集的完整流程(Python+OpenCV)

本文详细介绍了USB摄像头开发的完整流程,从参数配置到图像采集,使用Python和OpenCV实现。内容涵盖硬件原理、环境配置、参数调优及高级优化技巧,帮助开发者解决常见问题如分辨率设置、帧率控制和灯光频闪等,提升开发效率。

star的博客 235

c++ 运算符重载的例子

第一篇博文,来个简单点的运算符重载的例子:class Number{public: Number(int i) :x(i) { } Number&amp; operator++(int)     //后置方式重载++ { x+=2; return *this; } Number&amp; operator++() //前置方式重载++ { x+=3; return *this; } i...

weixin_41915560的博客 375

用python提取PDF中各类文本内容的方法

用python提取PDF中各类文本内容的方法

安静的软件工程师 6086

C++运算符重载例子代码

#include using namespace std; class Time { private: int h,m,s; public: Time(); Time(int mh,int mm,int ms); //重载++运算符 Time operator++(int); void ShowMe(); friend ostream&

yyf的博客 2204

【Linux命令大全】006.网络通讯之write命令(实操篇)

Linux write命令摘要 write是Linux系统中用于用户间实时通讯的命令工具,允许向其他登录用户的终端发送消息。主要功能包括: 基本使用:通过write username向指定用户发送消息,Ctrl+D结束输入 终端指定:当用户登录多个终端时,可用write username tty指定目标终端 实用技巧: 使用who查看在线用户 通过管道发送单行消息:echo "内容" | write user 支持多行消息发送和简单聊天会话。

yuhuasheng1997的博客 213

Jetson 平台编译安装 FFmpeg 7.1(支持 Nvmpi + SRT + x265)

摘要: 本文详细介绍了在NVIDIA Jetson平台上编译FFmpeg 7.1并集成关键功能的全过程。通过补丁方式加入Nvmpi实现硬件加速支持,同时编译集成x265编码器和SRT低延迟传输协议。步骤涵盖:1)安装x265编码器;2)配置SRT协议支持;3)编译jetson-ffmpeg的Nvmpi接口;4)定制化编译FFmpeg 7.1;5)验证模块集成情况。最终实现支持硬件编解码、高效HEVC压缩和可靠推流的增强版FFmpeg,为Jetson平台的音视频处理提供完整解决方案。

J。 345

c语言重载例子,C++常用的运算符重载例子

正好在学习运算符重载,随后整理了一下,此处不介绍理论知识,只是把所学系统的整理了一下,提供了例子供大家参考,类的定义和main()函数见最后。1.加法运算符+重载有两种方式(区别在于形参为一个还是两个):(1)作为类内的函数在public中进行成员函数声明:Sales_dataoperator+(constSales_data&SD1);在类外进行函数定义:Sales_dataSales_...

weixin_31011587的博客 635

(8)(8.19) GPIOs

Ardupilot官网关于《Copter》的翻译 —《(8.19) GPIOs》。

无人机开发(开源Ardupilot) 1万+

重载++运算符的例子

#include class coord{ int x,y; public: coord(int i=0,int j=0); void print(); coord operator ++(); }; coord::coord(int i,int j){ x=i;y=j; } void coord::print(){ cout<<" x= "<<x<<" ,y="<<y<<endl

little博客 399

Probability and Statistics - 4th edition

Probability and Statistics - 4th edition

假人有限元模型

假人模型,车辆碰撞假人有限元模型,适合做乘员安全的研究者利用

运算符重载的几个例子

1.二元运算符 二元运算符指的是一个运算符有左操作数和右操作数两个对象,比如常见的+、-、*、/等等 1)算术运算符:+、-、*、/、% 2)关系运算符:&lt;=、&gt;=、&lt;、&gt;、!=、== 3)位运算符:^、&amp;、| 4)逻辑运算符:&amp;&amp;、|| 以&gt;=为例: #include &lt;iostream&gt; using namesp...

renwu 1万+

迈瑞BS系列全自动生化分析仪LIS协议接口手册(内含HL7和ASTM)

迈瑞BS系列全自动生化分析仪LIS协议接口手册,内含HL7和ASTM)

运算符重载的一个例子

class MainClass{ struct Vector { public double x, y, z; public Vector(double x, double y, double z) { this.x = x; this.y = y; this.z = z;...

weixin_30446197的博客 86

SAP B1中文培訓教材_SDK

公司内部培训资料,对开发工具 ,DIAPI, UIAPI,Add-ON有详细解说

C# 运算符重载例子

重载自增运算符++ public class Person { public int age; public Person(int age) { this.age = age; } public static Person operator ++(Person ...

风风风儿带我飞的博客 522

c#中的运算符重载例子

下面的例子重载了+号,实现了两个矩形类相加 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication1 { class RectPrimary { ...

weixin_43935474的博客 391

运算符重载的例子

/// @file ClassroomExamples.cpp /// @brief 2015-1223课堂笔记的验证代码 #include #include #include "RMB.h" using namespace std; void clear_cin(); void fnTest_Operator_overloading(); int main(int argc, cha

博客标题不能为空 1134

运算符重载的几个小例子

1.坐标 : #include &amp;amp;amp;lt;iostream&amp;amp;amp;gt; using namespace std; /** * 定义Coordinate类 * 数据成员:m_iX,m_iY * 成员函数:构造函数 * 重载--运算符,重载+运算符 */ class Coordinate // 坐标 { public: Coordinate(int x, int y) { ...

Tattoo的博客 790

结构体重载==运算符小例子

编写工具:devC++测试环境:windows系统#include #include #include using namespace std;struct Sun{       int a;       string b;       bool operator==(const Sun sun1)       {            return (sun1.a==a && sun1.b==b

寥若晨星 1511

C++运算符重载详解及例子

如有转载请注明出处,本文原文地址:http://blog.youkuaiyun.com/dingyuanpu/article/details/5852825 C++中预定义的运算符的操作对象只能是基本数据类型,实际上,对于很多用户自定义类型,也需要有类似的运算操作。例如:  class complex  {   public:    complex(double r=0.0,double I=0

A_Ly的专栏 664

c++运算符重载例子精讲

我们都知道c语言中给两个任意数进行四则运算及比较大小非常容易,符号可以直接用,但在c++中,每个用到的类中数据都不能直接进行四则运算,要加类域,书写非常麻烦。可以采用运算符重载简化。下面举个例子。

2201_75999403的博客 164

C++学习笔记之运算符重载例子

本文重载前置--,后置--和运算符+。 代码如下: #include using namespace std; /** * 定义Coordinate类 * 数据成员:m_iX,m_iY * 成员函数:构造函数 * 重载--运算符,重载+运算符 */ class Coordinate { public: Coordinate(int x, int y) { m_i

ljp1919的专栏 3579

重载运算符中的const_C++运算符重载(例子附完整源码)

基本概念C++语言的一个很有意思的特性就是除了支持函数重载外还支持运算符重载,原因就是在C++看来运算符也算是一种函数。比如一个a + b 的加法表达式也可以用函数的形式:operator + (a, b)来表达。这里的operator +代表的就是加法函数。高级语言中的表达式和数学表达式非常相似,在一定的程度上通过运算符来描述表达式会比通过函数来描述表达式更加利于理解和阅读。一般情况下在重载某个...

weixin_39959369的博客 704

C#中运算符重载的例子

下边举了个运算符重载的例子 using System.Collections; using System.Collections.Generic; using UnityEngine; class Point { public int x; public int y; public static Point operator +(Point p1,Point p2) { Point p = new Point(); p.x = p1.x +

charlsdm的博客 305
上一篇: C++学习-入门到精通-【8】运算符重载:string类
下一篇: C++学习-入门到精通【9】面向对象编程:继承
YKPG
博客等级 码龄6年 344粉丝 37原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值