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

news2024/10/6 16:21:48

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.coloradmin.cn/o/1602181.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

【前端面试3+1】14 路由跳转的方式、如何取消已经发送的ajax请求、如何按顺序发起三个ajax请求并按顺序返回、【两个数组的并集】

一、路由跳转的几种方式 1、页面跳转 使用超链接 <a> 标签&#xff1a;通过在页面中定义超链接&#xff0c;用户点击超链接后会跳转到指定的URL页面。使用重定向&#xff1a;服务器端可以通过设置HTTP响应头中的Location字段&#xff0c;将用户重定向到指定的URL页面。使…

MySQL Prepared语句(Prepared Statements)

在数据库应用中&#xff0c;很多SQL语句都会重复执行很多次&#xff0c;每次执行可能只是where条件中的变量值不同&#xff0c;但MySQL依然会解析SQL语法并生成执行计划。对于这类情况&#xff0c;可以利用prepared语句来避免重复解析SQL的开销。 文章目录 一、prepared语句优…

职业技能鉴定服务中心(新闻系统+证书查询系统)

后端采用ThinkPHP8&#xff0c;最新tp框架 前端采用divcss布局 数据库采用MySQL 采用三种技术实现新闻系统和证书查询系统 源码&#xff1a;git clone https://gitee.com/3539949703/certificate-website.git 效果图如下&#xff1a;

2024年国内可用最强AI工具软件应用排行榜TOP8——优点和缺点

中国在2024年持续推动人工智能&#xff08;AI&#xff09;发展&#xff0c;受到政策、技术和市场的三重驱动。诞生了一批人工智能&#xff08;AI&#xff09;领域的新力军。我们通过对国内AI的逐一评测&#xff0c;从各个AI处理结果优略的角度&#xff0c;再结合网络上广大AI用…

bootstrap-select 搜索过滤输入中文问题,前2个字母输入转成空格

bootstrap是v3.3.7的 v1.6.3版本的bootstrap-select,注释以下2行 //that.$menu.find(li).filter(:visible:not(.divider)).eq(0).addClass(active).find(a).focus(); // $(this).focus();

学习在Debian系统上安装Shadowsocks教程

学习在Debian系统上安装Shadowsocks教程 安装shadowsocks-libev及其所需的依赖启动Shadowsocks服务&#xff1a;如果你想要通过代理本地流量&#xff0c;你可以使用ss-local&#xff1a;启动并设置ss-local&#xff1a;查看状态本地连接 安装shadowsocks-libev及其所需的依赖 …

mybatisPlus数据字段填充

这里用到的时实体类User import com.baomidou.mybatisplus.annotation.FieldFill; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableLogic; import com.baomidou.mybatisplus.annotation.TableName; import lombok.…

【Linux系统编程】第四弹---基本指令(二)

✨个人主页&#xff1a; 熬夜学编程的小林 &#x1f497;系列专栏&#xff1a; 【C语言详解】 【数据结构详解】【C详解】【Linux系统编程】 目录 1、echo指令 2、cat指令 3、more指令 4、less指令 4、head指令 5、tail指令 6、时间相关的指令 7、cal指令 8、find指…

Python数据结构【二】查找

前言 可私聊进一千多人Python全栈交流群&#xff08;手把手教学&#xff0c;问题解答&#xff09; 进群可领取Python全栈教程视频 多得数不过来的计算机书籍&#xff1a;基础、Web、爬虫、数据分析、可视化、机器学习、深度学习、人工智能、算法、面试题等。 &#x1f680;&a…

【JSON2WEB】 13 基于REST2SQL 和 Amis 的 SQL 查询分析器

【JSON2WEB】01 WEB管理信息系统架构设计 【JSON2WEB】02 JSON2WEB初步UI设计 【JSON2WEB】03 go的模板包html/template的使用 【JSON2WEB】04 amis低代码前端框架介绍 【JSON2WEB】05 前端开发三件套 HTML CSS JavaScript 速成 【JSON2WEB】06 JSON2WEB前端框架搭建 【J…

【迅为iMX6Q】开发板 Linux version 6.6.3 SD卡 启动

开发环境 win10 64位 VMware Workstation Pro 16 ubuntu 20.04 【迅为imx6q】开发板&#xff0c; 2G DDR RAM linux-imx 下载 使用 NXP 官方提供的 linux-imx&#xff0c;代码地址为&#xff1a; https://github.com/nxp-imx/linux-imx 使用 git 下载 linux-imx&#xff…

磁盘管理和文件系统

一.磁盘基础 1.磁盘结构 &#xff08;1&#xff09;物理结构&#xff1a; 盘片&#xff1a;硬盘有多个盘片&#xff0c;每盘片2面 磁头&#xff1a;每面一个磁头 &#xff08;2&#xff09;硬盘的数据结构 扇区&#xff1a;盘片被分为多个扇形区域&#xff0c;每个扇区存…

有爱有乐有知识,还有《米小圈上学记》!

“读万卷书&#xff0c;不如行万里路”&#xff0c;说的是读再多的书&#xff0c;也比不上走过万水千山所得。可是又有几人能得尝山水之妙&#xff0c;大多被困于尘世中。我虽走过一些山水&#xff0c;但大多因生存困于一隅&#xff0c;不得随心而行。 然而&#xff0c;读书也…

实景三维技术在社区服务与管理领域的应用

随着科技的不断发展&#xff0c;实景三维技术已经成为了社区服务与管理领域的一项重要工具。实景三维技术可以通过高精度的三维建模技术&#xff0c;将现实世界中的场景、物体以及人物进行数字化重建&#xff0c;使得人们可以在计算机中实现对现实世界的全方位、多角度的观察和…

【重磅开源】一款可以生成SpringBoot+Vue代码的轻量级项目

基于SpringBootVue3开发的轻量级快速开发脚手架 &#x1f341;项目简介 一款通用的前、后端项目模板 一款快速开发管理系统的项目 一款可以生成SpringBootVue代码的项目 一款持续迭代的开源项目 一个程序员的心血合集 度过严寒&#xff0c;终有春日&#xff…

WEB前端-笔记

目录 一、字体 二、背景图片 三、显示方式 四、类型转换 五、相对定位 六、绝对定位 七、固定定位 八、Index 九、粘性定位 十、内边距 十一、外边距 十二、边框 十三、盒子尺寸计算问题 十四、清楚默认样式 十五、内容溢出 十六、外边距的尺寸与坍塌 十七、行…

Spring @Transactional 注解

官方文档&#xff1a;https://docs.spring.io/spring-framework/reference/data-access/transaction/declarative/annotations.html#:~:textThe%20%40Transactional%20annotation%20is%20metadata,suspending%20any%20existing%20transaction%22). 推荐阅读&#xff1a;https:…

基于STM32的智能垃圾分类识别系统设计(论文)_kaic

摘 要 智能垃圾分类技术逐渐受到了政府的重视和支持&#xff0c;越来越多的城市开始推行垃圾分类政策。因此设计一款能够对垃圾进行识别并分类的控制系统具有一定的现实意义。本设计采用STM32单片机作为整个系统的控制核心&#xff0c;利用K210开发板作为图像识别控制系统&…

RT-thread信号量与互斥量

1,信号量 信号量是一种轻型的用于解决线程间同步问题的内核对象,线程可以获取或释放它,从而达到同步或互斥的目的。理解资源计数适合于线程间工作处理速度不匹配的场合;信号量在大于0时才能获取,在中断、线程中均可释放信号量。 为了体现使用信号量来达到线程间的同步,…

删除链表的倒数第n个节点【java版】

思路&#xff1a;要删除链表的倒数第n个节点&#xff0c;只需要找到倒数第n1个节点然后改变他的指针即可! 问题转换为&#xff1a;找到倒数第n1个节点? 假设要删除倒数第2个节点&#xff0c;只需要找到倒数第3个节点&#xff0c;问题是如何定位到这个节点 可见一个指针是不够…