C++——类和对象3|日期类型|Cout运算符重载|Cin运算符重载|const成员|(下)

简介: 笔记

实现Cin运算符重载


cin是istream类型对象,流提取,cout不需要改变Date,但Cin需要改变Date

因为这是要从流里面提取出年月日参数,放到日期里面

1.png2.png

但此时输入非法日期不报错

3.png

根据日期算星期

以1年1月1日星期六为参考对象,输入一个日期后,俩日期相减,然后对7取模就行

0相当于周天,1-5对应周一到周六

void DateSwap()
{
  const char* WeekDayToStr[] = { "周一","周二","周三","周四","周五","周六","周日" };
  Date d1;
  Date start(1, 1, 1);
  cout << "请输入日期";
  cin >> d1;
  int n = d1 - start;
  int weekDay = 0;
  weekDay += n;
  cout << WeekDayToStr[ weekDay % 7] << endl;
}

4.png修改后


完整代码  


Date.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:
  // 获取某年某月的天数
  int GetMonthDay(int year, int month)
  {
    static int days[13] = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
    int day = days[month];
    if (month == 2
      && ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)))
    {
      day += 1;
    }
    return day;
  }
  Date(int year = 1900, int month = 1, int day = 1)
  {
    _year = year;
    _month = month;
    _day = day;
    if (!CheckDate())
    {
      Print();
      cout << "日期非法" << endl;
    }
  }
  bool CheckDate()
  {
    if (_year >= 1 && _month < 13 && _month>0 && _day > 0 && _day <= GetMonthDay(_year, _month))
      return true;
    else
      return false;
  }
  void Print();
  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 operator+(int day);
  Date& operator++();//默认是前置++,返回+完后的值,用引用返回
  Date operator++(int i);//后前置++,里面要写一个参数,这里的参数可以不用形参接收,括号里直接写int就行,但加了参数也无所谓,这里的参数只是为了区分
  //C++为了区分前后置++,使用重载进行区分,后置++重载增加一个int参数跟前置构成函数重载进行区分
  Date& operator+=(int day);
  Date operator-(int day);
  Date& operator-= (int day);
  Date& operator--();
  Date  operator--(int);
  int operator-(const Date& d);
private:
  int _year;
  int _month;
  int _day;
};
inline ostream& operator<<(ostream& out, const Date& d)
{
  out << d._year <<"年" << d._month<< "月" << d._day<<"日" << endl;
  return out;
}
inline istream& operator>>(istream & in, Date & d)
{
  assert(d.CheckDate());
    in >> d._year >> d._month >> d._day;
    return in;
}
void DateSwap();

Date.cpp

#include"date.h"
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);
}
bool Date::operator>(const Date& d)
{
  if (_year > d._year)
    return true;
  else if (_year == d._year && _month > d._month)
  {
    return true;
  }
  else if (_year == d._year && _month == d._month && _day > d._day)
  {
    return true;
  }
  else
    return false;
}
bool Date::operator<(const Date& d)
{
  return !(*this >= d);
}
bool Date::operator>=(const Date& d)
{
  return (*this > d) || (*this == d);
}
bool Date::operator<=(const Date& d)
{
  return !(*this > d);
}
// 自身要改变
Date&  Date::operator+=(int day)
{
  if (day < 0)
  {
    return *this -= -day;
  }
  _day += day;
  while (_day > GetMonthDay(_year, _month))
  {
    _day -= GetMonthDay(_year, _month);
    _month++;
    if (_month == 13)
    {
      _month = 1;
      _year ++;
    }
  }
  return *this;
}
//自身不改变
Date  Date::operator+(int day)
{
  Date ret(*this);//拷贝构造
  //Date ret= *this;在这里,这条语句是拷贝构造,拿*this初始化ret,已经存在的对线才是赋值
  ret += day;
  return ret;//传值返回的时候,会生成一份拷贝
}
void  Date::Print()
{
  cout << _year<<"/" << _month<<"/"<<_day << endl;
}
Date& Date::operator++()//前置
{
  *this += 1;
  return *this;
}
Date Date::operator++(int)//后置,返回++之前的值
{
  Date tmp(*this);
  *this += 1;
  return tmp;
}
Date& Date::operator-= (int day)
{
  if (day < 0)
  {
    return *this += -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 ret = *this;
  ret -= day;
  return ret;
}
Date& Date::operator--()//前置--
{
  *this -= 1;
  return *this;
}
Date   Date::operator--(int)//后置--
{
  Date tmp = *this;
  *this -= 1;
  return tmp;
}
int  Date::operator-(const Date& d)//日期相减
{
  int flag = 1;
  Date max = *this;
  Date min = d;
  if (*this < d)
  {
    min = *this;
    max = d;
    flag = -1;
  }
  int n = 0;
  while (min != max)
  {
    ++min;
    ++n;
  }
  return n*flag;
}
void DateSwap()
{
  const char* WeekDayToStr[] = { "周一","周二","周三","周四","周五","周六","周日" };
  Date d1;
  Date start(1, 1, 1);
  cout << "请输入日期";
  cin >> d1;
  int n = d1 - start;
  int weekDay = 0;
  weekDay += n;
  cout << WeekDayToStr[ weekDay % 7] << endl;
}
//void Date::operator<<(ostream& out)
//{
//  out << _year << "-" << _month <<"-" << _day;
//}

const成员


5.png

这种情况下会报错 ,会把const Date转换为Date

这是因为this指针在传参的时候是这样的

6.png

参数里的const修饰this指针本身

d1.Print();传参的时候是将d1的地址传过去,&d1,类型是Date*

d2.Print();&d2 传不过去,因为传过去的是const Date*类型,而形参是Date*类型

7.png

d1<d2可以,d2<d1不可以

8.png

d1<d2,d1是Date *可以传过去


d2<d1,d2是const Date *不能传给this,所以会报错


如果要改变这种错误,就要给this加上const,Date *const this变为const Date *const this


把const加在这个位置

9.png

0.png

但是对于d1,本来是Date *const this变为了const Date *const this 把权限缩小了,这样d1就不能给赋值了

10.png

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


权限可以缩小,平移,不能放大

这里可以写俩个Print,构成函数重载

11.png12.png

编译器在调用的时候会自动匹配,当取地址情况下需要它们同时存在


Date* operator&()
  {
  return this;
  }
  const Date* operator&()const
  {
  return this;
  }

一个返回Date *,一个返回const Date *


13.png

调用相对应的

如果不写编译器会自动生成

14.png15.png

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

如果不想让别人取地址,一般自己写一个,返回nullptr即可


习题  计算日期到天数转换



16.png

#include <iostream>
using namespace std;
int main(){
int year,month,day;
    cin>>year>>month>>day;
    int monthDays[13]={0,31,59,90,120,151,181,212,243,273,304,334,365};
    int n=monthDays[month-1]+day;
    if(month>2&&((year%4==0&&year%100!=0)||(year%400==0)))
        n+=1;
       cout<<n<<endl;
    return 0;
}
相关文章
|
6月前
|
人工智能 机器人 编译器
c++模板初阶----函数模板与类模板
class 类模板名private://类内成员声明class Apublic:A(T val):a(val){}private:T a;return 0;运行结果:注意:类模板中的成员函数若是放在类外定义时,需要加模板参数列表。return 0;
191 0
|
6月前
|
存储 编译器 程序员
c++的类(附含explicit关键字,友元,内部类)
本文介绍了C++中类的核心概念与用法,涵盖封装、继承、多态三大特性。重点讲解了类的定义(`class`与`struct`)、访问限定符(`private`、`public`、`protected`)、类的作用域及成员函数的声明与定义分离。同时深入探讨了类的大小计算、`this`指针、默认成员函数(构造函数、析构函数、拷贝构造、赋值重载)以及运算符重载等内容。 文章还详细分析了`explicit`关键字的作用、静态成员(变量与函数)、友元(友元函数与友元类)的概念及其使用场景,并简要介绍了内部类的特性。
291 0
|
8月前
|
编译器 C++ 容器
【c++11】c++11新特性(上)(列表初始化、右值引用和移动语义、类的新默认成员函数、lambda表达式)
C++11为C++带来了革命性变化,引入了列表初始化、右值引用、移动语义、类的新默认成员函数和lambda表达式等特性。列表初始化统一了对象初始化方式,initializer_list简化了容器多元素初始化;右值引用和移动语义优化了资源管理,减少拷贝开销;类新增移动构造和移动赋值函数提升性能;lambda表达式提供匿名函数对象,增强代码简洁性和灵活性。这些特性共同推动了现代C++编程的发展,提升了开发效率与程序性能。
343 12
|
9月前
|
编译器 C++
类和对象(下)C++
本内容主要讲解C++中的初始化列表、类型转换、静态成员、友元、内部类、匿名对象及对象拷贝时的编译器优化。初始化列表用于成员变量定义初始化,尤其对引用、const及无默认构造函数的类类型变量至关重要。类型转换中,`explicit`可禁用隐式转换。静态成员属类而非对象,受访问限定符约束。内部类是独立类,可增强封装性。匿名对象生命周期短,常用于临时场景。编译器会优化对象拷贝以提高效率。最后,鼓励大家通过重复练习提升技能!
|
10月前
|
编译器 C++ 开发者
【C++篇】深度解析类与对象(下)
在上一篇博客中,我们学习了C++的基础类与对象概念,包括类的定义、对象的使用和构造函数的作用。在这一篇,我们将深入探讨C++类的一些重要特性,如构造函数的高级用法、类型转换、static成员、友元、内部类、匿名对象,以及对象拷贝优化等。这些内容可以帮助你更好地理解和应用面向对象编程的核心理念,提升代码的健壮性、灵活性和可维护性。
|
9月前
|
设计模式 安全 C++
【C++进阶】特殊类设计 && 单例模式
通过对特殊类设计和单例模式的深入探讨,我们可以更好地设计和实现复杂的C++程序。特殊类设计提高了代码的安全性和可维护性,而单例模式则确保类的唯一实例性和全局访问性。理解并掌握这些高级设计技巧,对于提升C++编程水平至关重要。
192 16
|
10月前
|
编译器 C语言 C++
类和对象的简述(c++篇)
类和对象的简述(c++篇)
|
9月前
|
编译器 C++
类和对象(中 )C++
本文详细讲解了C++中的默认成员函数,包括构造函数、析构函数、拷贝构造函数、赋值运算符重载和取地址运算符重载等内容。重点分析了各函数的特点、使用场景及相互关系,如构造函数的主要任务是初始化对象,而非创建空间;析构函数用于清理资源;拷贝构造与赋值运算符的区别在于前者用于创建新对象,后者用于已存在的对象赋值。同时,文章还探讨了运算符重载的规则及其应用场景,并通过实例加深理解。最后强调,若类中存在资源管理,需显式定义拷贝构造和赋值运算符以避免浅拷贝问题。
|
9月前
|
存储 编译器 C++
类和对象(上)(C++)
本篇内容主要讲解了C++中类的相关知识,包括类的定义、实例化及this指针的作用。详细说明了类的定义格式、成员函数默认为inline、访问限定符(public、protected、private)的使用规则,以及class与struct的区别。同时分析了类实例化的概念,对象大小的计算规则和内存对齐原则。最后介绍了this指针的工作机制,解释了成员函数如何通过隐含的this指针区分不同对象的数据。这些知识点帮助我们更好地理解C++中类的封装性和对象的实现原理。
|
9月前
|
安全 C++
【c++】继承(继承的定义格式、赋值兼容转换、多继承、派生类默认成员函数规则、继承与友元、继承与静态成员)
本文深入探讨了C++中的继承机制,作为面向对象编程(OOP)的核心特性之一。继承通过允许派生类扩展基类的属性和方法,极大促进了代码复用,增强了代码的可维护性和可扩展性。文章详细介绍了继承的基本概念、定义格式、继承方式(public、protected、private)、赋值兼容转换、作用域问题、默认成员函数规则、继承与友元、静态成员、多继承及菱形继承问题,并对比了继承与组合的优缺点。最后总结指出,虽然继承提高了代码灵活性和复用率,但也带来了耦合度高的问题,建议在“has-a”和“is-a”关系同时存在时优先使用组合。
504 6