C++练级之路——类和对象(中二)

1、运算符重载

        C++为了增强代码的可读性引入了运算符重载,运算符重载是具有特殊函数名的函数,也是具有其返回值类型,函数名字以及参数列表,其返回值类型和参数列表与普通的函数类似。

函数名字为:关键字operator后面接需要重载的运算符符号;

函数原型:返回值类型 operator操作符(参数列表)。

注意:

1.不能通过链接其他符号来创建新的操作符:比如 operator@;

2.重载操作符必须有一个类类型参数;

3.用于内置类型的运算符,其含义不能改变,例如:内置类型的+,不能改变其含义;

4.作为类成员函数重载时,其形参看起来比操作书数数目少1,因为成员函数的第一个参数为隐藏的this;

5.  .*   ::     sizeof     ?:    .    注意以上五个运算符不能重载,这个经常在笔试选择题中出现。

//运算符重载
bool operator<(const Date& d);
bool operator==(const Date& d);
bool operator<=(const Date& d);
bool operator>(const Date& d);
bool operator>=(const Date& d);
bool operator!=(const Date& d);

//函数实现
bool Date::operator<(const Date& d)
{
	if (_year < d._year)
		return true;

	else if (_year == d._year)
	{
		if (_month < d._month)
			return true;

		else if (_month == d._month)
			return _day < d._day;
	}
	return false;
}

bool Date::operator==(const Date& d)
{
	return _year == d._year
		&& _month == d._month
		&& _day == d._day;
}

bool Date::operator<=(const Date& d)
{
	return *this < d && *this == d;
}
bool Date::operator>(const Date& d)
{
	return !(*this <= d);
}
bool Date::operator>=(const Date& d)
{
	return !(*this <d);
}
bool Date::operator!=(const Date& d)
{
	return !(*this == d);
}

        当我们重载了  <  和 ==  时,就可以复用这两个运算符,重载<=  >   >=   != ,更加方便了。

2、赋值运算符重载 

1、赋值运算符重载格式

1.参数类型:const  参数名&,传递引用可以提高传参效率,(不用再调用拷贝构造了);

2.返回值类型:参数名&  返回引用可以提高返回的效率,有返回值的目的是为了支持连续赋值;

3.检测是否自己给自己赋值

4.返回trhis,要符合连续赋值的含义;

//声明
Date& operator=(const Date& d);

//定义
Date& Date:: operator=(const Date& d)
{
	_year = d._year;
	_month = d._month;
	_day = d._day;
	return *this;
}

 2、赋值运算符只能重载成成员函数,不能重载成全局函数

因为赋值运算符第一个参数是this指针,重载成全局函数,就需要传this指针,而当类里面没有显式定义赋值运算符时,编译器会自动生成一个默认的。此时就会和类外的赋值运算符重载形成冲突,所以赋值运算符只能是成员函数。

3、用户没有显式实现时,编译器会自动生成一个默认的赋值操作符重载,以值的方式逐字节拷贝

注意:内置类型成员变量是直接赋值的,而自定义成员变量需要调用对应类的赋值运算符重载完成赋值,如果自定义类中没有显式实现赋值运算符重载,编译器也会默认生成赋值重载;

class Time
{
public:
	Time()
	{
		_hour = 1;
		_minute = 1;
		_second = 1;
	}
    //这个赋值运算符重载写不写都可以,不写的话编译器也会自动生成
	/*Time& operator=(const Time& t)
	{
		if (this != &t)
		{
			_hour = t._hour;
			_minute = t._minute;
			_second = t._second;
		}
		return *this;
	}*/
	
//private:
	int _hour;
	int _minute;
	int _second;
};

class Date1
{
public:
	void print()
	{
		cout << _year << "-" << _month << "-" << _day << endl;
	}
private:
	// 基本类型(内置类型)
	int _year = 1970;
	int _month = 1;
	int _day = 1;
	// 自定义类型
	Time _t;
};
int main()
{
	Date1 d1;
	Date1 d2;
	d1 = d2;

	d1.print();
	d2.print();
	return 0;
}

但是,我们真的不需要自己写了吗?

不是的,如果类中涉及到资源管理,开辟空间的,就要自己实现赋值重载了,因为编译器自己实现的是浅拷贝,也就是值拷贝,不会额外开辟空间,所以我们自己写深拷贝,和拷贝构造,析构函数差不多

3、前置++和后置++重载

前置++,返回+1之后的结果,

注意:this指向的对象函数结束后不会销毁,故用引用的方式返回提高效率;

后置++,返回+1之前的结果

为了能够区分

C++规定:后置++重载时多增加一个Int 参数,但调用函数时,用户不用传递,编译器会自动传递,(问就是C++规定的)

后置++,要用值的方式返回,因为要在函数内创建一个临时对象tem来保存*this,然后*this++

然后返回tem,

//前置++
Date& Date::operator++()
{
	*this += 1;
	return *this;
}

//后置++
//int 只是一个标志,代表他是后置的--,没有实际意义
Date Date::operator++(int)
{
	Date tem = *this;
	*this += 1;
	return tem;
}

//前置--
Date& Date::operator--()
{
	*this -= 1;
	return *this;
}

//后置--
Date Date::operator--(int)
{
	Date tem = *this;
	*this -= 1;
	return tem;
}

 4、const成员变量

将const修饰的成员函数成为“const成员函数”,,const修饰类成员函数,实际上是修饰该类成员函数隐函的 this 指针,表明在该成员函数中不能对类的成员进行修改。

class Date1
{
public:
	Date1(int year, int month, int day)
	{
		_year = year;
		_month = month;
		_day = day;
	}
	void Print()
	{
		cout << "Print()" << endl;
		cout << "year:" << _year << endl;
		cout << "month:" << _month << endl;
		cout << "day:" << _day << endl << endl;
	}
	void Print() const
	{
		cout << "Print()const" << endl;
		cout << "year:" << _year << endl;
		cout << "month:" << _month << endl;
		cout << "day:" << _day << endl << endl;
	}
private:
	int _year; // 年
	int _month; // 月
	int _day; // 日
};
void Test()
{
	Date1 d1(2022, 1, 13);
	d1.Print();
	const Date1 d2(2022, 1, 13);
	d2.Print();
}
  int main()
{
	  Test();
	  return 0;
}

 注意:权限可以缩小,平移,但是不可以放大;

请思考下面的几个问题:

1. const 对象可以调用非 const 成员函数吗?
2. const 对象可以调用 const 成员函数吗?
3. const 成员函数内可以调用其它的非 const 成员函数吗?
4. const 成员函数内可以调用其它的 const 成员函数吗?

5、日期类的实现

        我们还可以重载流插入和流提取

流插入我们要要在类外实现,因为在类中实现,第一个参数是隐形的this指针,而我们希望第一个参数是ostream& out,那我们就定义在类外可以解决这个问题,但是定义在类外我们就无法访问类中的私有的成员变量,就用到了另一个办法,友元,友元的概念就是我是你的朋友,我可以访问你的元素,不管是共有还是私有,这里暂且了解一下,下节会讲;

下面来看日期类的实现,上面的运算符重载都会用到;

//Date.h
#pragma once
#include<iostream>
using namespace std;

int is_year(int y);

class Date
{
	friend ostream& operator<<(ostream& out, const Date& d);
	friend istream& operator>>(istream& in, Date& d);
public:

	Date(int year=1 ,int month=1, int day=1);
	Date(const Date& d);
	//在类里面定义的函数默认就内联函数
	int GetMonthDay(int y, int m)
	{               
		static int months[13] = { 0,31,28,31,30,31,30,31,31,30,31,30,31 };
		if (m == 2)
			return months[m] + is_year(y);
		return months[m];
	}

	//日期+=天数
	Date& operator+=(int day);
	Date operator+(int day);
	Date& operator-=(int day);
	Date operator-(int day);

	//++和--
	Date& operator++();
	Date operator++(int);
	Date& operator--();
	Date operator--(int);

	//日期-日期
	int operator-(const Date& d);


	//运算符重载
	Date& operator=(const Date& d);
	bool operator<(const Date& d);
	bool operator==(const Date& d);
	bool operator<=(const Date& d);
	bool operator>(const Date& d);
	bool operator>=(const Date& d);
	bool operator!=(const Date& d);


	//流插入和流输出
	~Date();
	void print();

private:
	int _year;
	int _month;
	int _day;
};

ostream& operator<<(ostream& out, const Date& d);
istream& operator>>(istream& in,  Date& d);

//Date.cpp

#include"Date.h"


int is_year(int y)
{
	if (y % 4 == 0 && y % 100 != 0 || y % 400 == 0)
		return 1;
	return 0;
}
	Date::Date(int year , int month , int day )
	{
		_year = year;
		_month = month;
		_day = day;
	}
	Date::Date(const Date& d)
	{
		cout << "Date::Date(const Date& d)" << endl;
		_year = d._year;
		_month = d._month;
		_day = d._day;
	}
		
	Date& Date::operator+=(int day)
	{
		_day += day;
		while (_day > GetMonthDay(_year, _month))
		{
			_day -= GetMonthDay(_year, _month);
			_month++;
			if (_month == 13)
			{
				_year++;
				_month = 1;
			}
		}
		return *this;
	}

	Date Date::operator+(int day)
	{
		Date tem = *this;
		tem += day;
		return tem;
	}

	Date& Date::operator-=(int day)
	{
		_day -=day;
		while (_day < 0)
		{
			_month--;
			if (_month == 0)
			{
				_year--;
				_month = 12;
			}
			_day += GetMonthDay(_year, _month);
		}
		return *this;
	}

	Date Date::operator-(int day)
	{
		Date tem = *this;
		tem -= day;
		return tem;
	}


	//前置++
	Date& Date::operator++()
	{
		*this += 1;
		return *this;
	}

	//后置++
	//int 只是一个标志,代表他是后置的--,没有实际意义
	Date Date::operator++(int)
	{
		Date tem = *this;
		*this += 1;
		return tem;
	}

	//前置--
	Date& Date::operator--()
	{
		*this -= 1;
		return *this;
	}

	//后置--
	Date Date::operator--(int)
	{
		Date tem = *this;
		*this -= 1;
		return tem;
	}

	//日期-日期
	int Date:: operator-(const Date& d)
	{
		Date max = *this;
		Date min = d;
		int n = 0;
		int flag = 1;
		if (max < min)
		{
			max = d;
			min = *this;
			flag = -1;
		}

		while (min!=max)
		{
			++min;
			++ n;
		}
		return n*flag;                                                 
	}



	//赋值运算符重载
	Date& Date:: operator=(const Date& d)
	{
		_year = d._year;
		_month = d._month;
		_day = d._day;
		return *this;
	}

	bool Date::operator<(const Date& d)
	{
		if (_year < d._year)
			return true;

		else if (_year == d._year)
		{
			if (_month < d._month)
				return true;

			else if (_month == d._month)
				return _day < d._day;
		}
		return false;
	}

	bool Date::operator==(const Date& d)
	{
		return _year == d._year
			&& _month == d._month
			&& _day == d._day;
	}

	bool Date::operator<=(const Date& d)
	{
		return *this < d && *this == d;
	}
	bool Date::operator>(const Date& d)
	{
		return !(*this <= d);
	}
	bool Date::operator>=(const Date& d)
	{
		return !(*this <d);
	}
	bool Date::operator!=(const Date& d)
	{
		return !(*this == d);
	}

	void Date::print()
	{
		cout << _year << "-" << _month << "-" << _day << endl;
	}
	Date::~Date()
	{
		//cout << "Date::~Date()" << endl;

	}

	ostream& operator<<(ostream& out, const Date& d)
	{
		out << d._year << "年" << d._month << "月" << d._day << endl;
		return out;
	}

	istream& operator>>(istream& in, Date& d)
	{
		cout << "请输入日期:" << endl;

		in >> d._year >> d._month >> d._day;

		return in;
	}


//Test.cpp
#include"Date.h"

//Date func()
//{
//	Date d3(2024, 4, 14);
//	return d3;
//}
int fx()
{
	int a = 10;
	int b = 20;
	int c = 30;
	return a + b + c;
}
//int main()
//{
//	
//	  Date ret = func();
//	  ret.print();
//
//
//	/*Date d1(2024, 4, 14);
//	Date d2(2024, 5, 14);
//	d1.print();
//	d2.print();
//	cout << (d2 < d1) << endl;
//	cout << (d2 <= d1) << endl;
//	cout << (d2 > d1) << endl;
//	cout << (d2 >= d1) << endl;
//	cout << (d2 == d1) << endl;
//	cout << (d2 != d1) << endl;*/
//
//	return 0;
//}

//Date func()
//{
//	Date d3(2024, 4, 14);
//	return d3;
//}
//Date& func()
//{
//	Date d3(2024, 4, 14);
//	return d3;
//}
//int main()
//{
//	//const Date& ret = func();
//	//ret.print();
//
//	return 0;
//}

//Date& func()
//{
//	static Date d3(2024, 4, 14);
//	return d3;
//}
//int main()
//{
//	 Date& ret = func();
//	 ret.print();
//
//	return 0;
//}
//class Time
//{
//public:
//	Time()
//	{
//		_hour = 1;
//		_minute = 1;
//		_second = 1;
//	}
//	/*Time& operator=(const Time& t)
//	{
//		if (this != &t)
//		{
//			_hour = t._hour;
//			_minute = t._minute;
//			_second = t._second;
//		}
//		return *this;
//	}*/
//	
private:
//	int _hour;
//	int _minute;
//	int _second;
//};
//
//class Date1
//{
//public:
//	void print()
//	{
//		cout << _year << "-" << _month << "-" << _day << endl;
//	}
//private:
//	// 基本类型(内置类型)
//	int _year = 1970;
//	int _month = 1;
//	int _day = 1;
//	// 自定义类型
//	Time _t;
//};
//int main()
//{
//	Date1 d1;
//	Date1 d2;
//	d1 = d2;
//
//	d1.print();
//	d2.print();
//	return 0;
//}
//int main()
//{
//	Date d1(2024, 4, 15);
//	Date d2(2024, 2, 15);
//	d2 = d1;
//
//	d1.print();
//	d2.print();
//
//	
//	return 0;
//}




//class Date1
//{
//public:
//	Date1(int year, int month, int day)
//	{
//		_year = year;
//		_month = month;
//		_day = day;
//	}
//	void Print()
//	{
//		cout << "Print()" << endl;
//		cout << "year:" << _year << endl;
//		cout << "month:" << _month << endl;
//		cout << "day:" << _day << endl << endl;
//	}
//	void Print() const
//	{
//		cout << "Print()const" << endl;
//		cout << "year:" << _year << endl;
//		cout << "month:" << _month << endl;
//		cout << "day:" << _day << endl << endl;
//	}
//private:
//	int _year; // 年
//	int _month; // 月
//	int _day; // 日
//};
//void Test()
//{
//	Date1 d1(2022, 1, 13);
//	d1.Print();
//	const Date1 d2(2022, 1, 13);
//	d2.Print();
//}
//  int main()
//{
//	  Test();
//	  return 0;
//}
int main()
{
	Date d1(2024, 4, 17);
	Date d2(2024, 9, 14);

	cin >> d1 >> d2;
	cout << d1 << d2;
	/*cout << (d2 - d1) << endl;

	d1.print();
	d2.print();*/
	return 0;
}

6、取地址及const取地址操作符重载

这两个默认构造函数一般不用重新定义,编译器会默认生成;

class Date1
{
public:
	Date1* operator&()
	{
		return this;
	}
	const Date1* operator&()const
	{
		return this;
	}
private:
	int _year;
	int _month;
	int _day;
};

 这两个运算符一般不需要重载,使用编译器默认生成的取地址重载即可,除非特殊情况,比如想让别人获取到指定的内容!

撒花!!!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/551768.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

华为ensp中静态路由和默认路由的原理及配置

作者主页&#xff1a;点击&#xff01; ENSP专栏&#xff1a;点击&#xff01; 创作时间&#xff1a;2024年4月17日17点37分 默认路由 [Router] ip route-static <目的网络> <目的网络掩码> <下一跳地址>默认路由的作用是将无法匹配路由表中其他路由表项的…

储能的全生命周期成本即平准化度电成本的计算方法及python实践

1. 平准化度电成本&#xff08;LCOE&#xff09;是一种衡量电力项目经济性的指标 LCOE&#xff08;Levelized Cost of Energy,&#xff09;的概念最早由美国国家可再生能源实验室&#xff08;NREL&#xff09;在1995年提出&#xff0c;它是通过将一个项目生命周期内的所有成本…

公司微信公众号怎么创建?

公众号已经成为企业、品牌、个人IP与粉丝互动的重要平台。今天&#xff0c;伯乐网络传媒就来深入探讨如何巧妙地创建属于自己的微信公众号&#xff0c;为公司或品牌打造一个线上影响力的坚实基石。 一、注册微信公众号 第一步&#xff1a;访问微信公众平台官网 第二步&#x…

27.5k star!微软开源的项目,他好像真的想教会你 AI【文末带源码】

AI 和机器学习&#xff08;ML&#xff09;的发展正在改变我们的世界&#xff0c;从智能助手到自动驾驶汽车&#xff0c;无所不在。对于我的读者朋友来说&#xff0c;大家肯定是多多少少的使用过各种 AI 工具。然而&#xff0c;AI 和 ML 背后的工作机制究竟是什么样的呢&#xf…

volatile

volatile&#xff1a; 用来声明变量的关键字之一&#xff0c;它的主要作用是确保多个线程能够正确地处理共享变量。在多线程编程中&#xff0c;如果一个变量被多个线程共享并且这些线程可能同时修改该变量的值&#xff0c;那么就需要使用 volatile 关键字来保证线程之间对该变量…

IPV6——缓解地址池枯竭

目录 一.IPV6的来源 二.关于IPV6 1.’无限‘的地址空间 2.简化报文头部 3.层次化结构设计 4.即插即用 5.安全特性 6.Qos特性 三.IP v4&#xff0c;IP v6报文头部 IP v4 重点—TTL&#xff08;Time to live&#xff09; —— 存活时间&#xff0c;用于三层防环&#…

二维码电子画册制作教程,教你如何做出高端作品!

当今社会&#xff0c;二维码已经成为了信息传递的重要方式之一&#xff0c;其在电子商务、广告营销、活动推广等领域广泛应用。而如何将二维码巧妙地融入电子画册中&#xff0c;制作出高端、具有吸引力的作品&#xff0c;成为了许多设计师和营销人员关注的焦点 但是很多人却不知…

K8s的亲和、反亲和、污点、容忍

1 亲和与反亲和 亲和性的原理其实很简单&#xff0c;主要利用label标签结合nodeSelector选择器来实现 1.1 Pod和Node 从pod出发&#xff0c;可以分成亲和性和反亲和性&#xff0c;分别对应podAffinity和podAntiAffinity。从node出发&#xff0c;也可以分成亲和性和反亲和性&…

FANUC机器人通过ROBOGUIDE实现与实际的机器人进行程序导入导出的具体方法示例

FANUC机器人通过ROBOGUIDE实现与实际的机器人进行程序导入导出的具体方法示例 如下图所示,在电脑的开始菜单中找到”Robot Neiborhood”,点击进入, 如下图所示,设置要连接的机器人名称和主机IP地址(要确保自己的电脑和机器人IP地址在同一网段内),点击Add添加, 添加在线…

[Qt网络编程]之获取基本网络信息

前言 获取主机的网络地址和接口信息是进行网络编程的第一步&#xff0c;也是网络编程的基础。Qt提供了网络接口类 QNetworkInterface、网络地址人口类 QNetworkAddressEntry 和主机地址类 QHostAddress 来获取和使用地址信息。其中网络接口类 QNetworkInterface 描述了主机的卫…

光电水位开关数字信号与模拟信号的区别

如今随着液位检测技术的不断发展&#xff0c;检测液位的方法也越来越多&#xff0c;在小家电领域应用最多的液位检测方法就是光电液位传感器&#xff0c;光电液位传感器分为数字信号和模拟信号两种&#xff0c;都是输出高低电压信号&#xff0c;但输出的电压不一样。 数字信号…

OJ 连续数的和 球弹跳高度的计算【C判断是否为完全平方数】【格式输出%g输出全部小数部分】

连续数的和 判断是否为完全平方数有两种方法 1.遍历所有小于该数的整数&#xff0c;有一个满足平方与该数相等&#xff0c;则是完全平方数 2.用sqrt()或pow()函数对该数开方&#xff0c;取整&#xff08;舍去小数部分&#xff09;&#xff0c;再平方&#xff0c;与该数相等则…

项目7-音乐播放器4

1.喜欢/收藏音乐模块设计 1.1 请求响应模块设计 请求&#xff1a; { post, /lovemusic/likeMusic data: id//音乐id } 响应&#xff1a; { "status": 0, "message": "点赞音乐成功", "da…

力扣:120. 三角形最小路径和

力扣&#xff1a;120. 三角形最小路径和 给定一个三角形 triangle &#xff0c;找出自顶向下的最小路径和。 每一步只能移动到下一行中相邻的结点上。相邻的结点 在这里指的是 下标 与 上一层结点下标 相同或者等于 上一层结点下标 1 的两个结点。也就是说&#xff0c;如果正…

特殊文件-XML文件

简介 XML全称&#xff1a;Etensible Markup Language&#xff0c;可扩展标记语言 特点 标签都是成对出现的&#xff0c;一个标签就是一个元素一个xml文件中有且只有一个根标签标签也是可以携带属性的 IDEA创建XML 简单示例 必须有抬头标签是可以携带属性的&#xff0c;但是属性…

c++程序员简历中项目怎么写?避免踩坑!

C开发 9 年&#xff0c;目前人在大厂&#xff0c;做 C 相关的开发&#xff0c;作为资深 C 面试官&#xff0c;我来聊聊面试官眼中的校招简历中的 C 项目吧&#xff0c;希望对各位学弟学妹有帮助。 1. 简历中如何介绍自己的项目&#xff1f; 从面试官的角度来说&#xff0c;我…

QAnything部署Mac m1环境

本次安装时Qanything已经更新到了v1.3.3&#xff0c;支持纯python安装。安装过程比较简单&#xff0c;如下&#xff1a; QAnything/README_zh.md at qanything-python-v1.3.1 netease-youdao/QAnything GitHub 首先需要用Anaconda3创建隔离环境&#xff0c;简要说明下Anaco…

中型企业用CRM管理软件,求推荐?

中型企业是指哪些企业呢&#xff1f; 指的是员工人数在数百至数千人之间&#xff0c;年营业额在几千万至数亿元之间的企业。这些企业通常已经形成了较为稳定的业务模式和市场定位&#xff0c;有一定的市场份额和客户基础&#xff0c;同时也在积极拓展新的业务领域和市场空间。…

工业控制(ICS)---OMRON

OMRON FINS 欧姆龙厂商 命令代码(Command CODE)特别多&#xff0c;主要关注读写相关&#xff0c;如&#xff1a; Memory Area Read (0x0101) Memory Area Write (0x0102) Multiple Memory Area Read (0x0104) Memory Area Transfer (0x0105) Parameter Area Read (0x0201) Pa…

搜维尔科技:【工业仿真】煤矿安全知识基础学习VR系统

产品概述 煤矿安全知识基础学习VR系统 系统内容&#xff1a; 煤矿安全知识基础学习VR系统内容包括&#xff1a;下井流程&#xff08;正确乘坐罐笼、班前会、井下行走注意事项、工作服穿戴、入井检身及人员清点、下井前准备工作、提升运输安全&#xff09;&#xff1b;运煤流程…
最新文章