一些运算符重载的例子

TexGen模型导出ABAQUS inp文件时纱线材料属性缺失?5分钟快速修复指南 本文针对TexGen模型导出ABAQUS inp文件时纱线材料属性缺失的问题,提供了快速修复指南。通过手动编辑inp文件或使用Python脚本自动补全材料属性,帮助复合材料仿真工程师高效解决问题。文章还介绍了TexGen导出前的预防性设置和ABAQUS中的验证技巧,确保仿真分析的准确性。 阅读详情

一些运算符重载的例子



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类中的加法操作,大家还可以参照上面的形式,补充其他运算。

Roboguide与TIA V16通讯 阅读详情

相关推荐

C51编程25-应用篇(单片机与电脑端实现wifi通讯)

单片机使用ESP-01S wifi模块与电脑端进行数据通讯。

qq_34343637的博客 1万+

运算符重载例子

#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

S32DS3.5图形化配置实战:从零构建S32K144通信接口工程

本文详细介绍了如何使用S32DS3.5图形化配置工具从零构建S32K144通信接口工程。通过实战演示引脚配置、时钟树设置、SPI接口搭建等关键步骤,帮助开发者快速掌握NXP S32K系列开发技巧,提升嵌入式开发效率。特别针对S32DS3.5版本的新特性进行了深度解析,包括智能代码生成和调试优化方法。

weixin_26834815的博客 200

运算符重载_例子

#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

DySAT+: Enhancing Dynamic Graph Representation Learning with Multi-Head Self-Attention and Temporal-

本文深入探讨了DySAT+模型在动态图表示学习中的创新应用,通过多头时空注意力机制和层级信息融合策略,有效解决了动态图数据中的时间维度信息捕捉和结构演变动态适应问题。该模型在社交网络异常检测和金融交易网络分析等场景中表现出色,显著提升了预测准确率和响应速度。

weixin_29035405的博客 335

深入了解torch框架

大国的游戏,政府支持到位,是未来;AI : Artificial Intelligence,旨在研究、开发能够模拟、延伸和扩展人类智能的理论、方法、技术及应用系统,是一种拥有自主学习和推理能力的技术。它模仿人类大脑某些功能,包括感知、学习、理解、决策和问题解决。AI本质​ NLP(说话,听)、CV(眼睛)、自动驾驶、机器人(肢体动作)、大模型三要素:数据、网络、算力① 神经网络:找到合适的数学公式;② 训练:用已有数据训练网络,目标是求最优解;③ 推理:用模型预测新样本;PyTorch,简称Torch

qq_74732076的博客 1135

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

SAP 采购申请、采购订单的审批策略

采购申请、采购订单的审批策略 采购申请审批 PR审批可以分为:含分类、无分类 1、无分类PR审批: A、后台配置: 设置批准代码(批准代码可以设置多级审批): 发布批准标识使用系统已有的 “2 询价/采购订单”: 新建采购申请审批策略Z1(仅设置1级审批,一共可以设置8级审......

willieyuan的博客 2万+

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

【AUTOSAR-COM】-5.2-“Deadline Monitoring超时监控”-2-基于IPdu实现

目录 1 在CFG中配置Deadline Monitoring超时监控 1.1 参数说明 1.2 生成代码差异 2 通过一段测试代码看Deadline Monitoring超时监控 3 使用CAN盒观察Deadline Monitoring实际测试效果 3.1 Case 1:ECU开始工作时,没有收到Frame 3.2 Case 2:ECU工作中,接收的Frame丢失、 4 小结 5 结尾 关键字: DM=Deadline Monitoring超时监控 ComFirstTime...

「汽车电子助手」的博客 1788

RK35X8调试YT8531单网口千兆以太网PHY芯片,修复ping不通或者IP地址丢失的问题

RK35X8上调试YT8531以太网PHY

荻夜的博客 3976

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

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

weixin_31011587的博客 635

如何在多 GPU 配置上运行 Unsloth:数据并行或模型并行

当工作负载受限于内存(模型或批次无法放入单张显卡)、或受限于计算且计算与通信比率较高时(即每块 GPU 的额外计算量超过同步参数的开销,如在 DDP 中,或超过传递激活值的开销,如在模型并行中),多 GPU 配置才开始显现优势。在松散连接的显卡上(尤其是 PCIe 版本的 H100 或 A100),额外的设备间数据传输会导致性能显著低于单 GPU 运行。让我们厘清概念,明确说明如何通过模型并行(将模型拆分到多个 GPU)或数据并行(在每个 GPU 上复制模型)来跨多 GPU 运行 Unsloth。

人工智能领域专家 645

重载++运算符的例子

#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

ET2012新版免狗免安装绿色软件

ET2012新版免狗免安祖昂绿色软件。,新界面,新视觉,

数学建模模型总结

这是本人在两年内准备参加数学建模竞赛搜集到的模型资料,已经经过了本人的筛选和整理,希望能够对准备参加数学建模竞赛的学弟学妹们提供一些帮助!

运算符重载的几个例子

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

renwu 1万+

VB摄像头监控

该VB模块可对摄像头捕获的画面进行录像等,可在创建的窗口进行控制

运算符重载的一个例子

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

efm32 入门.pdf

本PDF共计22页,介绍的是操作驱动API,下载与否自己斟酌。

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、付费专栏及课程。

余额充值