C++类和对象(四)——类的实现、const、explicit、static

2024-04-14 02:12

本文主要是介绍C++类和对象(四)——类的实现、const、explicit、static,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

1. 日期类的实现(包括前置++和后置++)

Date.h

#pragma once
#include<iostream>
#include<assert.h>
using namespace std;class Date
{
public:bool CheckInvalid() const;Date(int year = 1, int month = 1, int day = 1);bool operator<(const Date& d) const;bool operator<=(const Date& d) const;bool operator>(const Date& d) const;bool operator>=(const Date& d) const;bool operator==(const Date& d) const;bool operator!=(const Date& d) const;// 日期加等天数Date& operator+=(int day);// 日期加天数Date operator+(int day) const;// 日期减等天数Date& operator-=(int day);// 日期减天数Date operator-(int day) const;// 前置++Date& operator++();// 后置++,特殊情况,给一个int形参,强行构成重载进行区分Date operator++(int);// 前置--Date& operator--();// 后置--,特殊情况,给一个int形参,强行构成重载进行区分Date operator--(int);// 日期减日期,整型函数重载int operator-(const Date& d);// 本质就是linline,获取当前月天数int GetMonthDay(int year, int month){assert(month > 0 && month < 13);static int monthDays[13] = { 0, 31, 28, 31, 30, 31, 30, 31, 31 ,30, 31 , 30, 31 };// 闰年判断if (month == 2 && ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0))){return 29;}return monthDays[month];}void Print()const  // 不加const,会发生权限放大,类型为Date*,需要变为const Date*,在C++中写法为在函数后边加const{cout << _year << "/" << _month << "/" << _day << endl;}// 如果写成成员函数,隐式传this,那么this占据了第一个参数,Date必须是左操作数,流方向就返了,且this还不可更改// 因此该运算符重载不能写成员函数,要写成全局函数,才能控制Date和流方向/*void operator<<(ostream& out){out << _year << "年" << _month << "月" << _day << "日" << endl;}*/// 友元声明,它被允许访问类的私有成员// 友元声明的语法是使用 friend 关键字,后面跟着函数原型。friend ostream& operator<<(ostream& out, const Date& d);friend istream& operator>>(istream& in, Date& d);private:int _year;int _month;int _day;
};
// 输出流运算符重载
ostream& operator<<(ostream& out, const Date& d);
istream& operator>>(istream& in, Date& d); // 不能加const

Data.cpp 

#define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
using namespace std;
#include"Date.h"Date::Date(int year, int month, int day){_year = year;_month = month;_day = day;if (!CheckInvalid()){cout << "构造日期非法" << endl;}}bool Date::operator<(const Date& d) const
{if (_year < d._year){return true;}else if (_year == d._year){if (_month < d._month){return true;}else if (_month == d._month){if (_day < d._day){return true;}}}return false;
}bool Date::operator<=(const Date& d) const
{return *this < d || *this == d;
}bool Date::operator>(const Date& d) const
{return !(*this <= d);
}bool Date::operator>=(const Date& d) const
{return !(*this < d);
}bool Date::operator==(const Date& d) const
{return _year == d._year&& _month == d._month&& _day == d._day;
}bool Date::operator!=(const Date& d) const
{return !(*this == d);
}// 日期加等天数
Date& Date::operator+=(int day)
{_day += day;while (_day > GetMonthDay(_year, _month)){_day = _day - GetMonthDay(_year, _month);++_month;if (_month == 13){++_year;_month = 1;}}return *this;}// 日期加天数
Date Date::operator+(int day) const
{//Date tmp(*this);// 拷贝构造//tmp._day += day;//while (tmp._day > GetMonthDay(tmp._year, tmp._month))//{//	tmp._day = tmp._day - GetMonthDay(tmp._year, tmp._month);//	++tmp._month;//	if (tmp._month == 13)//	{//		++tmp._year;//		tmp._month = 1;//	}//}//return tmp;Date tmp = *this; // 拷贝构造tmp += day; // 直接调用+=return tmp;}// 日期减等天数
Date& Date::operator-=(int day)
{_day -= day;while (_day <= 0){--_month;if (_month == 0){--_year;}_day = GetMonthDay(_year, _month);}return *this;
}Date Date::operator-(int day) const
{Date tmp = *this;tmp -= day;return tmp;
}// 前置++
Date& Date::operator++()
{*this += 1;return *this;
}
// 后置++,后置递增运算符返回的是递增前的值,而不是递增后的值
Date Date::operator++(int)
{Date tmp = *this;*this += 1;return tmp; //返回了递增前的临时对象tmp,而不是递增后的值
}// 前置--
Date& Date::operator--()
{*this -= 1;return *this;
}
// 后置--,特殊情况,给一个int形参,强行构成重载进行区分
Date Date::operator--(int)
{Date tmp = *this;*this -= 1;return tmp; //返回了递减前的临时对象tmp,而不是递减后的值
}// 日期减日期,整型函数重载
int Date::operator-(const Date& d)
{int flag = 1;Date max = *this;Date min = d;if (max < min){int flag = -1;Date max = d;Date min = *this;}int n = 0;while (min != max){++min;++n;}return n * flag;}bool Date::CheckInvalid() const
{if (_year <= 0 || _month < 1 || _month > 12 || _day < 1 || _day > 12){return false;}else{return true;}}ostream& operator<<(ostream& out, const Date& d)
{out << d._year << "年" << d._month << "月" << d._day << "日" << endl;return out;
}istream& operator>>(istream& in, Date& d)
{while (1){cout << "请以此输入年月日:>";in >> d._year >> d._month >> d._day;if (!d.CheckInvalid()){cout << "输入日期无效,请重新输入" << endl;}else{break;}}return in;}

实现一个+=后,其他的也可以调用该成员函数了,所以不需要重复写逻辑

前置++和后置++(--同):

为了强制构成重载,且需要区分前置和后置,后置++在成员函数中给一个int参数,调用的时候随便传一个int型的数就可以了

注意:前置++和后置++都是一元运算符,为了让前置++与后置++形成能正确重载

C++规定:后置++重载时多增加一个int类型的参数,但调用函数时该参数不用传递,编译器自动传递

注意:后置++是先使用后+1,因此需要返回+1之前的旧值,故需在实现时需要先将this保存 一份,然后给this+1

而temp是临时对象,因此只能以值的方式返回,不能返回引用

2. const成员

将const修饰的“成员函数”称之为const成员函数,const修饰类成员函数,实际修饰该成员函数隐含的this指针,表明在该成员函数中不能对类的任何成员进行修改

也就是说,该操作是对this的改变,因为this是隐式传递的,如果不加const便可直接调用函数,有改变this的风险,属于权限放大,这是不被允许的,加了const后属于权限的平移

class Date
{
public:Date(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()
{Date d1(2022,1,13);d1.Print();const Date d2(2022,1,13);d2.Print();
}

请思考下面的几个问题:

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

3. 取地址及const取地址操作符重载

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

class Date
{ 
public :Date* operator&(){return this;}const Date* operator&()const{return this ;}
private :int _year ; // 年int _month ; // 月int _day ; // 日
};

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

4. explicit关键字

构造函数不仅可以构造与初始化对象,对于单个参数或者除第一个参数无默认值其余均有默认值的构造函数,还具有类型转换的作用。

class Date
{
public:// 1. 单参构造函数,没有使用explicit修饰,具有类型转换作用// explicit修饰构造函数,禁止类型转换---explicit去掉之后,代码可以通过编译explicit Date(int year):_year(year){}/*// 2. 虽然有多个参数,但是创建对象时后两个参数可以不传递,没有使用explicit修饰,具
有类型转换作用// explicit修饰构造函数,禁止类型转换explicit Date(int year, int month = 1, int day = 1): _year(year), _month(month), _day(day){}*/Date& operator=(const Date& d){if (this != &d){_year = d._year;_month = d._month;_day = d._day;}return *this;}
private:int _year;int _month;int _day;
};
void Test()
{Date d1(2022);// 用一个整形变量给日期类型对象赋值// 实际编译器背后会用2023构造一个无名对象,最后用无名对象给d1对象进行赋值d1 = 2023;// 将1屏蔽掉,2放开时则编译失败,因为explicit修饰构造函数,禁止了单参构造函数类型转
换的作用
}

上述代码可读性不是很好,用explicit修饰构造函数,将会禁止构造函数的隐式转换。

5. static成员

声明为static的类成员称为类的静态成员,用static修饰的成员变量,称之为静态成员变量;用 static修饰的成员函数,称之为静态成员函数。静态成员变量一定要在类外进行初始化

面试题:实现一个类,计算程序中创建出了多少个类对象。

class A
{
public:A() { ++_scount; }A(const A& t) { ++_scount; }~A() { --_scount; }static int GetACount() { return _scount; }
private:static int _scount;
};
int A::_scount = 0;
void TestA()
{cout << A::GetACount() << endl;A a1, a2;A a3(a1);cout << A::GetACount() << endl;
}int main()
{TestA();return 0;
}
// 0
// 3

特性:

  1. 静态成员为所有类对象所共享,不属于某个具体的对象,存放在静态区
  2. 静态成员变量必须在类外定义,定义时不添加static关键字,类中只是声明
  3. 类静态成员即可用 类名::静态成员 或者 对象.静态成员 来访问
  4. 静态成员函数没有隐藏的this指针,不能访问任何非静态成员
  5. 静态成员也是类的成员,受public、protected、private 访问限定符的限制

【问题】

  1. 静态成员函数可以调用非静态成员函数吗?
  2. 非静态成员函数可以调用类的静态成员函数吗?

这篇关于C++类和对象(四)——类的实现、const、explicit、static的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/901834

相关文章

Python使用python-can实现合并BLF文件

《Python使用python-can实现合并BLF文件》python-can库是Python生态中专注于CAN总线通信与数据处理的强大工具,本文将使用python-can为BLF文件合并提供高效灵活... 目录一、python-can 库:CAN 数据处理的利器二、BLF 文件合并核心代码解析1. 基础合

Python使用OpenCV实现获取视频时长的小工具

《Python使用OpenCV实现获取视频时长的小工具》在处理视频数据时,获取视频的时长是一项常见且基础的需求,本文将详细介绍如何使用Python和OpenCV获取视频时长,并对每一行代码进行深入解析... 目录一、代码实现二、代码解析1. 导入 OpenCV 库2. 定义获取视频时长的函数3. 打开视频文

golang版本升级如何实现

《golang版本升级如何实现》:本文主要介绍golang版本升级如何实现问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录golanwww.chinasem.cng版本升级linux上golang版本升级删除golang旧版本安装golang最新版本总结gola

SpringBoot中SM2公钥加密、私钥解密的实现示例详解

《SpringBoot中SM2公钥加密、私钥解密的实现示例详解》本文介绍了如何在SpringBoot项目中实现SM2公钥加密和私钥解密的功能,通过使用Hutool库和BouncyCastle依赖,简化... 目录一、前言1、加密信息(示例)2、加密结果(示例)二、实现代码1、yml文件配置2、创建SM2工具

Mysql实现范围分区表(新增、删除、重组、查看)

《Mysql实现范围分区表(新增、删除、重组、查看)》MySQL分区表的四种类型(范围、哈希、列表、键值),主要介绍了范围分区的创建、查询、添加、删除及重组织操作,具有一定的参考价值,感兴趣的可以了解... 目录一、mysql分区表分类二、范围分区(Range Partitioning1、新建分区表:2、分

MySQL 定时新增分区的实现示例

《MySQL定时新增分区的实现示例》本文主要介绍了通过存储过程和定时任务实现MySQL分区的自动创建,解决大数据量下手动维护的繁琐问题,具有一定的参考价值,感兴趣的可以了解一下... mysql创建好分区之后,有时候会需要自动创建分区。比如,一些表数据量非常大,有些数据是热点数据,按照日期分区MululbU

MySQL中查找重复值的实现

《MySQL中查找重复值的实现》查找重复值是一项常见需求,比如在数据清理、数据分析、数据质量检查等场景下,我们常常需要找出表中某列或多列的重复值,具有一定的参考价值,感兴趣的可以了解一下... 目录技术背景实现步骤方法一:使用GROUP BY和HAVING子句方法二:仅返回重复值方法三:返回完整记录方法四:

IDEA中新建/切换Git分支的实现步骤

《IDEA中新建/切换Git分支的实现步骤》本文主要介绍了IDEA中新建/切换Git分支的实现步骤,通过菜单创建新分支并选择是否切换,创建后在Git详情或右键Checkout中切换分支,感兴趣的可以了... 前提:项目已被Git托管1、点击上方栏Git->NewBrancjsh...2、输入新的分支的

Python实现对阿里云OSS对象存储的操作详解

《Python实现对阿里云OSS对象存储的操作详解》这篇文章主要为大家详细介绍了Python实现对阿里云OSS对象存储的操作相关知识,包括连接,上传,下载,列举等功能,感兴趣的小伙伴可以了解下... 目录一、直接使用代码二、详细使用1. 环境准备2. 初始化配置3. bucket配置创建4. 文件上传到os

关于集合与数组转换实现方法

《关于集合与数组转换实现方法》:本文主要介绍关于集合与数组转换实现方法,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录1、Arrays.asList()1.1、方法作用1.2、内部实现1.3、修改元素的影响1.4、注意事项2、list.toArray()2.1、方