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

相关文章

使用animation.css库快速实现CSS3旋转动画效果

《使用animation.css库快速实现CSS3旋转动画效果》随着Web技术的不断发展,动画效果已经成为了网页设计中不可或缺的一部分,本文将深入探讨animation.css的工作原理,如何使用以及... 目录1. css3动画技术简介2. animation.css库介绍2.1 animation.cs

Java进行日期解析与格式化的实现代码

《Java进行日期解析与格式化的实现代码》使用Java搭配ApacheCommonsLang3和Natty库,可以实现灵活高效的日期解析与格式化,本文将通过相关示例为大家讲讲具体的实践操作,需要的可以... 目录一、背景二、依赖介绍1. Apache Commons Lang32. Natty三、核心实现代

SpringBoot实现接口数据加解密的三种实战方案

《SpringBoot实现接口数据加解密的三种实战方案》在金融支付、用户隐私信息传输等场景中,接口数据若以明文传输,极易被中间人攻击窃取,SpringBoot提供了多种优雅的加解密实现方案,本文将从原... 目录一、为什么需要接口数据加解密?二、核心加解密算法选择1. 对称加密(AES)2. 非对称加密(R

基于Go语言实现Base62编码的三种方式以及对比分析

《基于Go语言实现Base62编码的三种方式以及对比分析》Base62编码是一种在字符编码中使用62个字符的编码方式,在计算机科学中,,Go语言是一种静态类型、编译型语言,它由Google开发并开源,... 目录一、标准库现状与解决方案1. 标准库对比表2. 解决方案完整实现代码(含边界处理)二、关键实现细

python通过curl实现访问deepseek的API

《python通过curl实现访问deepseek的API》这篇文章主要为大家详细介绍了python如何通过curl实现访问deepseek的API,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编... API申请和充值下面是deepeek的API网站https://platform.deepsee

SpringBoot实现二维码生成的详细步骤与完整代码

《SpringBoot实现二维码生成的详细步骤与完整代码》如今,二维码的应用场景非常广泛,从支付到信息分享,二维码都扮演着重要角色,SpringBoot是一个非常流行的Java基于Spring框架的微... 目录一、环境搭建二、创建 Spring Boot 项目三、引入二维码生成依赖四、编写二维码生成代码五

MyBatisX逆向工程的实现示例

《MyBatisX逆向工程的实现示例》本文主要介绍了MyBatisX逆向工程的实现示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学... 目录逆向工程准备好数据库、表安装MyBATisX插件项目连接数据库引入依赖pom.XML生成实体类、

C++类和对象之初始化列表的使用方式

《C++类和对象之初始化列表的使用方式》:本文主要介绍C++类和对象之初始化列表的使用方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录C++初始化列表详解:性能优化与正确实践什么是初始化列表?初始化列表的三大核心作用1. 性能优化:避免不必要的赋值操作2. 强

C#实现查找并删除PDF中的空白页面

《C#实现查找并删除PDF中的空白页面》PDF文件中的空白页并不少见,因为它们有可能是作者有意留下的,也有可能是在处理文档时不小心添加的,下面我们来看看如何使用Spire.PDFfor.NET通过C#... 目录安装 Spire.PDF for .NETC# 查找并删除 PDF 文档中的空白页C# 添加与删

Java实现MinIO文件上传的加解密操作

《Java实现MinIO文件上传的加解密操作》在云存储场景中,数据安全是核心需求之一,MinIO作为高性能对象存储服务,支持通过客户端加密(CSE)在数据上传前完成加密,下面我们来看看如何通过Java... 目录一、背景与需求二、技术选型与原理1. 加密方案对比2. 核心算法选择三、完整代码实现1. 加密上