前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【C++修行之道】类和对象(五)日期类的实现、const成员、取地址及const和取地址操作符重载

【C++修行之道】类和对象(五)日期类的实现、const成员、取地址及const和取地址操作符重载

作者头像
走在努力路上的自己
发布2024-06-07 16:23:33
820
发布2024-06-07 16:23:33
举报

一、 日期类的实现

Date.h

代码语言:javascript
复制
#define  _CRT_SECURE_NO_WARNINGS 1
#pragma once
#include<iostream>
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<math.h>
#include<time.h>
#include<iostream>
#include<assert.h>

using namespace std;

class Date {

	// 友元函数声明
	friend ostream& operator<<(ostream& out, const Date& d);
	friend istream& operator>>(istream& in, Date& d);

public:

	// 全缺省的构造函数
	Date(int year = 1900, int month = 1, int day = 1);
	void Print() const;

	// 直接定义在类中,他默认是inline
	// 频繁调用
	// 获取某年某月的天数
	int GetMonthDay(int year, int month)
	{
		assert(month > 0 && month < 13);

		static int monthDayArray[13] = { -1,31,28,31,30,31,30,31,30,31,31,30,31 };
		if ((month == 2) && (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0))
			return 29;
		else
		{
			return monthDayArray[month];
		}
		return monthDayArray[month];
	}

	bool CheckDate();

	// 不使用引用修改成员的都能加上 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;
	bool operator!=(const Date& d) const;

	// 赋值运算符重载
	// d2 = d3 -> d2.operator=(&d2, d3)
	//Date& operator=(const Date& d);

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

	// d1 + 100
	// 日期+天数
	Date operator+(int day) const;


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

	// d1 - 100;
	// 日期-天数
	 Date operator-(int day) const;

	// d1 - d2
	// 日期-日期 返回天数
	int operator-(const Date& d) const;

	// ++d1
	Date& operator++();

	// d1++ -> d1.operator(1)
	// 为了区分,构成了重载,给后置++,强行增加了一个int形参
	// 这里不需要写形参名,因为接收值是多少不中呀,也不需要调用
	// 这个参数仅仅是为了前缀和后缀区分而存在的
	Date operator++(int);

	// --d1
	Date& operator--();

	// d1--
	Date operator--(int);

	 流插入
	//void operator<<(ostream& out);
	// 不建议, 因为Date* this占据了一个参数位置, 使用d<<cout不符合习惯
	

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

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

1.1 GetMonthDay函数(获取某年某月的天数)

代码语言:javascript
复制
// 获取某年某月的天数 
int GetMonthDay(int year, int month)  
{  
    // 断言:确保传入的月份是有效的  
    assert(month > 0 && month < 13);  
  
    // 存储了每个月通常的天数  
    static int monthDayArray[13] = { -1, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };  
  
    // 闰年检查:如果月份是2月,并且年份是闰年,则返回29天  
    if (month == 2 && ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0))) {  
        return 29;  
    }  
    // 如果不是2月或年份不是闰年,返回静态数组中存储的对应月份的天数  
    else {  
        return monthDayArray[month];  
    }  
}
问:这个函数为什么不和其他的函数一样放在Date.cpp文件中实现呢?
  • 内联函数的优化:在类定义中直接实现的成员函数默认为内联函数(inline)。内联函数通常用于减少函数调用的开销,因为它们在编译时会被“内联”到调用它们的代码中。GetMonthDay 函数可能预计会被频繁调用,这对于小型、频繁调用的函数特别有益,可以提高程序的执行效率。

1.2 CheckDate函数(检查日期有效性)、Print函数(打印日期)

代码语言:javascript
复制
bool Date::CheckDate()
{
	if (_month < 1 || _month > 12 // 检查_month成员变量是否小于1或大于12
    || _day < 1 || _day > GetMonthDay(_year, _month))
    // 检查_day成员变量是否小于1
    // 调用GetMonthDay(_year, _month)获取当前年份和月份对应的天数,并检查_day是否大于这个值 
	{
		return false;
	}
	else
	{
		return true;
	}
}

// Date类的构造函数,用于初始化Date对象
Date::Date(int year, int month, int day)
{
	_year = year;
	_month = month;
	_day = day;
    
    // 调用CheckDate函数检查日期是否合法
	if (!CheckDate())
	{
		cout << "日期非法" << endl;
	}
}

// 打印日期
void Date::Print() const
{
	cout << _year << "-" << _month << "-" << _day << "\n";
}

1.3 实现日期类的逻辑运算符重载

只需实现两个运算符,就能借助这两个运算符去简易的实现其他运算符。

<运算符的重载
代码语言:javascript
复制
// d1 < d2
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)
		{
			return _day < d._day;
		}
	}
	return false;
}
==运算符重载
代码语言:javascript
复制
// d1 == d2
bool Date::operator==(const Date& d) const
{
	return _year == d._year
		&& _month == d._month
		&& _day == d._day;
}
其他运算符重载
代码语言:javascript
复制
// d1 <= d2
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 !(*this == d);
}

1.4 日期与天数加减操作符重载

代码语言:javascript
复制
// d1 += 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;
}

// 1970以后
// d1 -= 100
Date& Date::operator-=(int day)
{
	if (day < 0)
	{
		return *this += -day;
	}

	_day -= day;
	while (_day <= 0)// 借位
	{
		--_month;
		if (_month == 0)
		{
			_month = 12;
			_year--;
		}

		//借上一个月的天数
		_day += GetMonthDay(_year, _month);
	}

	return *this;
}
  • += 和 -= 是复合赋值运算符。
  • 功能:复合运算符直接修改调用它们的对象。在Date类的上下文中,+= 运算符将指定的天数加到当前日期上,并直接修改该日期对象。同样,-= 运算符从当前日期中减去指定的天数。
  • 效率:由于不需要创建新对象,复合运算符在性能上可能更高效,特别是在需要频繁更新日期的场景中。
代码语言:javascript
复制
Date Date::operator-(int day) const
{
	Date tmp = *this;
	tmp -= day;
	return tmp;
}

Date Date::operator+(int day) const
{
	Date tmp = *this;
	tmp += day;
	return tmp;
}
  • + 和 - 是普通运算符
  • 功能:普通运算符不直接修改调用它们的对象,而是返回一个新的对象,该对象是原始对象与指定值进行运算后的结果。
  • 效率:由于需要创建新对象,因此在性能上可能略低于复合运算符。

1.5 日期相减时的操作符重载

代码语言:javascript
复制
// d1 - d2
int Date::operator-(const Date& d) const
{
	Date max = *this;
	Date min = d;
	int flag = 1;

	if (*this < d) // 确定最大和最小日期
	{
		max = d;
		min = *this;
		flag = -1;
        // 即当前对象小于传入的日期,则得到负数天数差
	}

	int n = 0;
	while (min != max)// 实现日期的 != 重载
	{
		++min;
		++n;
	}

	return n * flag;
}
  • 当前对象的日期早于传入的日期对象。此时,将max设置为d,min设置为*this,并将flag设置为-1。这意味着最终的天数差将是负数。
  • 在while循环体内,每次迭代都会对min进行自增操作(通过++运算符重载实现),同时计数器n也自增。这个过程会一直持续到min和max相等,即两个日期相同为止。

1.6 前置运算符和后置运算符实现的区别

代码语言:javascript
复制
// ++d1
Date& Date::operator++()
{
	*this += 1;
	return *this;
}

// d1++ -> d1.operator(1)
// 为了区分,构成了重载,给后置++,强行增加了一个int形参
// 这里不需要写形参名,因为接收值是多少不重要,也不需要调用
// 这个参数仅仅是为了前缀和后缀区分而存在的
Date Date::operator++(int)
{
	Date tmp(*this);
	*this += 1;
	return tmp;
}

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

// d1--
Date Date::operator--(int)
{
	Date tmp = *this;
	*this -= 1;
	return tmp;
}

为了区分,构成了重载,给后置++,强行增加了一个int形参。

代码语言:javascript
复制
Date Date::operator++(int)

这里不需要写形参名,因为接收值是多少不重要,也不需要调用。 这个参数仅仅是为了前缀和后缀区分而存在的。

前置运算符的语义是“先操作,再返回”。
  • 语义上:前置运算符的语义是先对对象进行递作,然后返回操作后的对象。这里的关键是“操作后的对象”。
  • 效率:返回引用避免了不必要的创建和返回对象的拷贝。在C++中,对象的复制可能是一个昂贵的操作。
  • 链式操作:通过返回引用,可以支持链式操作。例如,可以这样写代码:--date = anotherDate;
  • 注意:this指向的对象函数结束后不会销毁,故以引用方式返回提高效率
后置运算符的语义是“先返回,再操作”。
  • 语义上:后置运算符的语义是先返回操作后的对象,然后对对象进行递作。后置运算符的关键在于返回操作前的状态。
  • 安全性:返回拷贝还避免了潜在的外部修改,此时得到的是一个独立的值,而不是对原始数据的直接引用。原始数据没有影响。
  • 前置++和后置++都是一元运算符,为了让前置++与后置++形成能正确重载 C++规定:后置++重载时多增加一个int类型的参数,但调用函数时该参数不用传递,编译器自动传递。
  • 注意:后置++是先使用后+1,因此需要返回+1之前的旧值,故需在实现时需要先将this保存一份,然后给this + 1。
  • 而temp是临时对象,因此只能以值的方式返回,不能返回引用

1.7 输入输出流重载

代码语言:javascript
复制
// 友元函数声明,声明后可访问私有成员变量
friend ostream& operator<<(ostream& out, const Date& d);
friend istream& operator>>(istream& in, Date& d);

// 重载输出流操作符<<,用于将Date对象以特定格式输出到输出流中
ostream& operator<<(ostream& out, const Date& d)
{
    // 向输出流中输出Date对象的年份、月份和日期,并添加中文字符和换行符进行格式化
	out << d._year << "年" << d._month << "月" << d._day << "日" << endl;
    // 返回输出流的引用,以便支持链式调用
	return out;
}

// 重载输入流操作符>>,用于从输入流中读取数据并设置到Date对象中
istream& operator>>(istream& in, Date& d)
{
	cout << "请依次输入年月日:>";
	in >> d._year >> d._month >> d._day;
    
    // 调用Date对象的CheckDate()方法检查输入的日期是否合法 
	if (!d.CheckDate())
	{
		cout << "日期非法" << endl;
	}
    
    // 返回输入流的引用,以便支持链式调用
	return in;
}
为什么参数顺序为(ostream& out, const Date& d)?
  • 标准的流插入运算符 << 是左结合的,也就是说左侧应该是流对象(如 cout),右侧是我们想要输出的对象(如 Date)。改变参数顺序后,调用方式也必须相应改变即(<< cout),这与常规用法不符。

标准库中的 operator<< 已经定义好了左侧是 ostream&,右侧是要输出的对象。改变参数顺序后,编译器不会再将其识别为流插入运算符,导致无法正常使用链式调用等特性。

operator<< 的参数顺序反过来会导致函数不能正常作为流插入运算符使用,破坏标准库的调用方式和使用习惯。

二、const成员

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

我们来看看下面的代码

代码语言:javascript
复制
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成员函数吗?

const对象不能调用非const成员函数。

  • 当你将一个对象声明为const时,实际上是在承诺不会修改这个对象的状态。因此,只能对这个对象调用const成员函数,因为这些函数承诺不会修改对象的状态。

2. 非const对象可以调用const成员函数吗?

const对象可以调用const成员函数。

  • const成员函数的主要目的是确保函数不会修改对象的状态。因此,对于非const对象(即可以修改的对象)来说,调用const成员函数是安全的,因为即使对象本身可以被修改,const成员函数也承诺不会修改它。

3. const成员函数内可以调用其它的非const成员函数吗?

不可以。在const成员函数中,不能直接调用同一个类的非const成员函数。原因是const成员函数承诺不会修改对象的状态,而如果它调用了非const成员函数,就会违背这个承诺,因为非const成员函数可能会修改对象。

然而,有一种情况可以间接调用非const成员函数,那就是如果你将对象的const性质通过const_cast去除,然后调用非const成员函数。但这种做法是不推荐的,因为它破坏了const的正确性和对象的常量性质,可能导致未定义行为或程序错误。通常来说,应该尽量避免这种做法。

总结来说,const成员函数内不能直接调用非const成员函数,以保持const成员函数的承诺不修改对象状态。

4. 非const成员函数内可以调用其它的const成员函数吗?

是的,非const成员函数内部可以调用const成员函数。

const成员函数的主要特点是它不会修改调用它的对象的状态。因此,从逻辑上讲,在可以修改对象状态的非const成员函数中调用一个不会修改对象状态的const成员函数是安全的。

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

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

代码语言:javascript
复制
class A
{
public:
	// 我们不实现,编译器会自己实现,我们实现了编译器就不会自己实现了
	// 一般不需要我们自己实现
	// 除非不想让别人取到这个类型对象的真实地址
	A* operator&()
	{
		cout << "A* operator&()" << endl;

		return nullptr;
	}

	const A* operator&() const
	{
		cout << "const A* operator&() const" << endl;

		return (const A*)0xffffffff;
	}
private:
	int _a1 = 1;
	int _a2 = 2;
	int _a3 = 3;
};

int main()
{
	A aa1;
	const A aa2;

	cout << &aa1 << endl;
	cout << &aa2 << endl;

	return 0;
}

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

今天就先到这了!!!

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2024-06-06,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 一、 日期类的实现
    • Date.h
      • 1.1 GetMonthDay函数(获取某年某月的天数)
        • 问:这个函数为什么不和其他的函数一样放在Date.cpp文件中实现呢?
      • 1.2 CheckDate函数(检查日期有效性)、Print函数(打印日期)
        • 1.3 实现日期类的逻辑运算符重载
          • <运算符的重载
          • ==运算符重载
          • 其他运算符重载
        • 1.4 日期与天数加减操作符重载
          • 1.5 日期相减时的操作符重载
            • 1.6 前置运算符和后置运算符实现的区别
              • 前置运算符的语义是“先操作,再返回”。
              • 后置运算符的语义是“先返回,再操作”。
            • 1.7 输入输出流重载
              • 为什么参数顺序为(ostream& out, const Date& d)?
          • 二、const成员
            • 请思考下面的几个问题:
              • 1. const对象可以调用非const成员函数吗?
                • 2. 非const对象可以调用const成员函数吗?
                  • 3. const成员函数内可以调用其它的非const成员函数吗?
                    • 4. 非const成员函数内可以调用其它的const成员函数吗?
                    • 三、取地址及const取地址操作符重载
                    领券
                    问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档