当前位置:   article > 正文

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

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

目录

一、 日期类的实现

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取地址操作符重载 


一、 日期类的实现

Date.h

  1. #define _CRT_SECURE_NO_WARNINGS 1
  2. #pragma once
  3. #include<iostream>
  4. #include<stdio.h>
  5. #include<string.h>
  6. #include<stdlib.h>
  7. #include<math.h>
  8. #include<time.h>
  9. #include<iostream>
  10. #include<assert.h>
  11. using namespace std;
  12. class Date {
  13. // 友元函数声明
  14. friend ostream& operator<<(ostream& out, const Date& d);
  15. friend istream& operator>>(istream& in, Date& d);
  16. public:
  17. // 全缺省的构造函数
  18. Date(int year = 1900, int month = 1, int day = 1);
  19. void Print() const;
  20. // 直接定义在类中,他默认是inline
  21. // 频繁调用
  22. // 获取某年某月的天数
  23. int GetMonthDay(int year, int month)
  24. {
  25. assert(month > 0 && month < 13);
  26. static int monthDayArray[13] = { -1,31,28,31,30,31,30,31,30,31,31,30,31 };
  27. if ((month == 2) && ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)))
  28. return 29;
  29. else
  30. {
  31. return monthDayArray[month];
  32. }
  33. return monthDayArray[month];
  34. }
  35. bool CheckDate();
  36. // 不使用引用修改成员的都能加上 const
  37. bool operator<(const Date& d) const;
  38. bool operator<=(const Date& d) const;
  39. bool operator>(const Date& d) const;
  40. bool operator>=(const Date& d) const;
  41. bool operator==(const Date& d) const;
  42. bool operator!=(const Date& d) const;
  43. // 赋值运算符重载
  44. // d2 = d3 -> d2.operator=(&d2, d3)
  45. //Date& operator=(const Date& d);
  46. // d1 += 100
  47. // 日期+=天数
  48. Date& operator+=(int day);
  49. // d1 + 100
  50. // 日期+天数
  51. Date operator+(int day) const;
  52. // d1 -= 100
  53. // 日期-=天数
  54. Date& operator-=(int day);
  55. // d1 - 100;
  56. // 日期-天数
  57. Date operator-(int day) const;
  58. // d1 - d2
  59. // 日期-日期 返回天数
  60. int operator-(const Date& d) const;
  61. // ++d1
  62. Date& operator++();
  63. // d1++ -> d1.operator(1)
  64. // 为了区分,构成了重载,给后置++,强行增加了一个int形参
  65. // 这里不需要写形参名,因为接收值是多少不中呀,也不需要调用
  66. // 这个参数仅仅是为了前缀和后缀区分而存在的
  67. Date operator++(int);
  68. // --d1
  69. Date& operator--();
  70. // d1--
  71. Date operator--(int);
  72. 流插入
  73. //void operator<<(ostream& out);
  74. // 不建议, 因为Date* this占据了一个参数位置, 使用d<<cout不符合习惯
  75. // private:
  76. int _year;
  77. int _month;
  78. int _day;
  79. };
  80. // 重载
  81. ostream& operator<<(ostream & out, const Date & d);
  82. istream& operator>>(istream& in, Date& d);

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

  1. // 获取某年某月的天数
  2. int GetMonthDay(int year, int month)
  3. {
  4. // 断言:确保传入的月份是有效的
  5. assert(month > 0 && month < 13);
  6. // 存储了每个月通常的天数
  7. static int monthDayArray[13] = { -1, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
  8. // 闰年检查:如果月份是2月,并且年份是闰年,则返回29天
  9. if (month == 2 && ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0))) {
  10. return 29;
  11. }
  12. // 如果不是2月或年份不是闰年,返回静态数组中存储的对应月份的天数
  13. else {
  14. return monthDayArray[month];
  15. }
  16. }

 问:这个函数为什么不和其他的函数一样放在Date.cpp文件中实现呢?

  • 内联函数的优化:在类定义中直接实现的成员函数默认为内联函数(inline)。内联函数通常用于减少函数调用的开销,因为它们在编译时会被“内联”到调用它们的代码中。GetMonthDay 函数可能预计会被频繁调用,这对于小型、频繁调用的函数特别有益,可以提高程序的执行效率。

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

  1. bool Date::CheckDate()
  2. {
  3. if (_month < 1 || _month > 12 // 检查_month成员变量是否小于1或大于12
  4. || _day < 1 || _day > GetMonthDay(_year, _month))
  5. // 检查_day成员变量是否小于1
  6. // 调用GetMonthDay(_year, _month)获取当前年份和月份对应的天数,并检查_day是否大于这个值
  7. {
  8. return false;
  9. }
  10. else
  11. {
  12. return true;
  13. }
  14. }
  15. // Date类的构造函数,用于初始化Date对象
  16. Date::Date(int year, int month, int day)
  17. {
  18. _year = year;
  19. _month = month;
  20. _day = day;
  21. // 调用CheckDate函数检查日期是否合法
  22. if (!CheckDate())
  23. {
  24. cout << "日期非法" << endl;
  25. }
  26. }
  27. // 打印日期
  28. void Date::Print() const
  29. {
  30. cout << _year << "-" << _month << "-" << _day << "\n";
  31. }

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

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

<运算符的重载

  1. // d1 < d2
  2. bool Date::operator<(const Date& d) const
  3. {
  4. if (_year < d._year)
  5. return true;
  6. else if (_year == d._year)
  7. {
  8. if (_month < d._month)
  9. return true;
  10. else if (_month < d._month)
  11. {
  12. return _day < d._day;
  13. }
  14. }
  15. return false;
  16. }

 ==运算符重载

  1. // d1 == d2
  2. bool Date::operator==(const Date& d) const
  3. {
  4. return _year == d._year
  5. && _month == d._month
  6. && _day == d._day;
  7. }

其他运算符重载 

  1. // d1 <= d2
  2. bool Date::operator<=(const Date& d) const
  3. {
  4. return *this < d || *this == d;
  5. }
  6. bool Date::operator>(const Date& d) const
  7. {
  8. return !(*this <= d);
  9. }
  10. bool Date::operator>=(const Date& d) const
  11. {
  12. return !(*this < d);
  13. }
  14. bool Date::operator!=(const Date& d) const
  15. {
  16. return !(*this == d);
  17. }

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

  1. // d1 += day
  2. Date& Date::operator+=(int day)
  3. {
  4. _day += day;
  5. while (_day > GetMonthDay(_year, _month))
  6. // 进位
  7. {
  8. _day -= GetMonthDay(_year, _month);
  9. ++_month;
  10. if (_month == 13)
  11. {
  12. ++_year;
  13. _month = 1;
  14. }
  15. }
  16. return *this;
  17. }
  18. // 1970以后
  19. // d1 -= 100
  20. Date& Date::operator-=(int day)
  21. {
  22. if (day < 0)
  23. {
  24. return *this += -day;
  25. }
  26. _day -= day;
  27. while (_day <= 0)// 借位
  28. {
  29. --_month;
  30. if (_month == 0)
  31. {
  32. _month = 12;
  33. _year--;
  34. }
  35. //借上一个月的天数
  36. _day += GetMonthDay(_year, _month);
  37. }
  38. return *this;
  39. }
  •  += 和 -= 是复合赋值运算符。
  • 功能:复合运算符直接修改调用它们的对象。在Date类的上下文中,+= 运算符将指定的天数加到当前日期上,并直接修改该日期对象。同样,-= 运算符从当前日期中减去指定的天数。
  • 效率:由于不需要创建新对象,复合运算符在性能上可能更高效,特别是在需要频繁更新日期的场景中。

 

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

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

  1. // d1 - d2
  2. int Date::operator-(const Date& d) const
  3. {
  4. Date max = *this;
  5. Date min = d;
  6. int flag = 1;
  7. if (*this < d) // 确定最大和最小日期
  8. {
  9. max = d;
  10. min = *this;
  11. flag = -1;
  12. // 即当前对象小于传入的日期,则得到负数天数差
  13. }
  14. int n = 0;
  15. while (min != max)// 实现日期的 != 重载
  16. {
  17. ++min;
  18. ++n;
  19. }
  20. return n * flag;
  21. }

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

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

  1. // ++d1
  2. Date& Date::operator++()
  3. {
  4. *this += 1;
  5. return *this;
  6. }
  7. // d1++ -> d1.operator(1)
  8. // 为了区分,构成了重载,给后置++,强行增加了一个int形参
  9. // 这里不需要写形参名,因为接收值是多少不重要,也不需要调用
  10. // 这个参数仅仅是为了前缀和后缀区分而存在的
  11. Date Date::operator++(int)
  12. {
  13. Date tmp(*this);
  14. *this += 1;
  15. return tmp;
  16. }
  17. // --d1
  18. Date& Date::operator--()
  19. {
  20. *this -= 1;
  21. return *this;
  22. }
  23. // d1--
  24. Date Date::operator--(int)
  25. {
  26. Date tmp = *this;
  27. *this -= 1;
  28. return tmp;
  29. }

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

Date Date::operator++(int)

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

前置运算符的语义是“先操作,再返回”。

  • 语义上:前置运算符的语义是先对对象进行递作,然后返回操作后的对象。这里的关键是“操作后的对象”
  • 效率:返回引用避免了不必要的创建和返回对象的拷贝。在C++中,对象的复制可能是一个昂贵的操作。
  • 链式操作:通过返回引用,可以支持链式操作。例如,可以这样写代码:--date = anotherDate; 
  • 注意:this指向的对象函数结束后不会销毁,故以引用方式返回提高效率

后置运算符的语义是“先返回,再操作”。

  • 语义上:后置运算符的语义是先返回操作后的对象,然后对对象进行递作。后置运算符的关键在于返回操作前的状态
  • 安全性:返回拷贝还避免了潜在的外部修改,此时得到的是一个独立的值,而不是对原始数据的直接引用。原始数据没有影响。
  • 前置++和后置++都是一元运算符,为了让前置++与后置++形成能正确重载
    C++规定:后置++重载时多增加一个int类型的参数,但调用函数时该参数不用传递,编译器自动传递。
  • 注意:后置++是先使用后+1,因此需要返回+1之前的旧值,故需在实现时需要先将this保存一份,然后给this + 1。
  • 而temp是临时对象,因此只能以值的方式返回,不能返回引用

1.7 输入输出流重载

  1. // 友元函数声明,声明后可访问私有成员变量
  2. friend ostream& operator<<(ostream& out, const Date& d);
  3. friend istream& operator>>(istream& in, Date& d);
  4. // 重载输出流操作符<<,用于将Date对象以特定格式输出到输出流中
  5. ostream& operator<<(ostream& out, const Date& d)
  6. {
  7. // 向输出流中输出Date对象的年份、月份和日期,并添加中文字符和换行符进行格式化
  8. out << d._year << "年" << d._month << "月" << d._day << "日" << endl;
  9. // 返回输出流的引用,以便支持链式调用
  10. return out;
  11. }
  12. // 重载输入流操作符>>,用于从输入流中读取数据并设置到Date对象中
  13. istream& operator>>(istream& in, Date& d)
  14. {
  15. cout << "请依次输入年月日:>";
  16. in >> d._year >> d._month >> d._day;
  17. // 调用Date对象的CheckDate()方法检查输入的日期是否合法
  18. if (!d.CheckDate())
  19. {
  20. cout << "日期非法" << endl;
  21. }
  22. // 返回输入流的引用,以便支持链式调用
  23. return in;
  24. }

为什么参数顺序为(ostream& out, const Date& d)?

  • 标准的流插入运算符 << 是左结合的,也就是说左侧应该是流对象(如 cout),右侧是我们想要输出的对象(如 Date)。改变参数顺序后,调用方式也必须相应改变即(<< cout),这与常规用法不符。

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

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

二、const成员

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

  1. class Date
  2. {
  3. public:
  4. Date(int year, int month, int day)
  5. {
  6. _year = year;
  7. _month = month;
  8. _day = day;
  9. }
  10. void Print()
  11. {
  12. cout << "Print()" << endl;
  13. cout << "year:" << _year << endl;
  14. cout << "month:" << _month << endl;
  15. cout << "day:" << _day << endl << endl;
  16. }
  17. void Print() const
  18. {
  19. cout << "Print()const" << endl;
  20. cout << "year:" << _year << endl;
  21. cout << "month:" << _month << endl;
  22. cout << "day:" << _day << endl << endl;
  23. }
  24. private:
  25. int _year; // 年
  26. int _month; // 月
  27. int _day; // 日
  28. };
  29. void Test()
  30. {
  31. Date d1(2022, 1, 13);
  32. d1.Print();
  33. const Date d2(2022, 1, 13);
  34. d2.Print();
  35. }

请思考下面的几个问题:

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取地址操作符重载 

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

  1. class A
  2. {
  3. public:
  4. // 我们不实现,编译器会自己实现,我们实现了编译器就不会自己实现了
  5. // 一般不需要我们自己实现
  6. // 除非不想让别人取到这个类型对象的真实地址
  7. A* operator&()
  8. {
  9. cout << "A* operator&()" << endl;
  10. return nullptr;
  11. }
  12. const A* operator&() const
  13. {
  14. cout << "const A* operator&() const" << endl;
  15. return (const A*)0xffffffff;
  16. }
  17. private:
  18. int _a1 = 1;
  19. int _a2 = 2;
  20. int _a3 = 3;
  21. };
  22. int main()
  23. {
  24. A aa1;
  25. const A aa2;
  26. cout << &aa1 << endl;
  27. cout << &aa2 << endl;
  28. return 0;
  29. }

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

今天就先到这了!!!

看到这里了还不给博主扣个:
⛳️ 点赞☀️收藏 ⭐️ 关注!

你们的点赞就是博主更新最大的动力!
有问题可以评论或者私信呢秒回哦。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/笔触狂放9/article/detail/728719
推荐阅读
相关标签
  

闽ICP备14008679号