【C++】—— 类和对象(中)一张图带你搞清楚6个默认成员函数+万字总结 复习全靠它(3)

简介: 【C++】—— 类和对象(中)一张图带你搞清楚6个默认成员函数+万字总结 复习全靠它(3)

五、日期类实现

1. 日期类的定义

class Date
{
public:
    //构造函数
  Date(int year = 1, int month = 1, int day = 1);
  //打印
  void Print() const;
  // 获取某年某月的天数
  int GetMonthDay(int year, int month);
  // >运算符重载
  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+(int day);
  // 日期 -= 天数
  Date& operator-=(int day);
  // 日期 - 天数
  Date operator-(int day);
  // 前置++
  Date& operator++();
  // 后置++; 后置为了跟前置++,进行区分,增加了一个参数占位,跟前置++,构成重载
  Date operator++(int);
  // 前置--
  Date& operator--();
  // 后置--
  Date operator--(int);
  // 日期-日期 返回天数
  int operator-(const Date& d);
  //获取某天是周几
  void PrintWeekDay();
private:
  int _year;
  int _month;
  int _day;
};

2.日期类的接口实现

①日期类的构造函数

  对于日期类,我们要对它的年、月、日进行初始化,我们可以采用全缺省的方式;一年有12个月,每个月的天数是不一样的,我们可以用一个数组来表示,最好给一个静态的数组,因为当我们每次实例化对象时,静态的数组只会初始化一次;但是此时还要考虑:给定的年月日是否合法和闰年、非闰年二月的天数情况。


       年的判断一定大于等于0、月一定是(0,12)、天数最主要的就是二月(闰年的判断);


       方法:


       1.可以采用if、else判断条件,把所有的情况都列举出来;


       2.也可以采用switch语句;相比第一种要好一些;


       3.就是用数组加上闰年的判断条件;对于数组个数,最好给到13个,下标是从0开始的,第一个元素就放0,后面的12个放相应月的天数,二月给28,当判断为闰年时,直接加1就可以了;因为是对类的私有成员的访问,我们将其实现为成员函数;

// 获取某年某月的天数
int Date::GetMonthDay(int year, int month)const
{
  static int monthDayArray[13] = { 0,31,28,31,30,31,30,31,31,30,31,30,31 };
  int day = monthDayArray[month];//获取每个月的天数
  if (month == 2 && ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)))
  {
    day += 1;//如果是二月并且是闰年,天数就加+1
  }
  return day;
}
//构造函数
Date::Date(int year, int month, int day)
{
  _year = year;
  _month = month;
  _day = day;
  if (!(_year >= 0
    && (month > 0 && month < 13)
    && (day > 0 && day <= GetMonthDay(year, month))))
  {
        //不满足年月日的条件,就是非法的
    cout << "非法日期->";
    Print();
  }
}
//打印
void Date::Print()const
{
  cout << _year << "-" << _month << "-" << _day << endl;
}

②日期类比较运算符重载

       对于日期类的运算符重载,不难实现;需要注意的地方:有6个比较运算符,我们只需要实现其中两个运算符(>和==),其他的直接复用即可;

// >运算符重载
bool Date::operator>(const Date& d)const
{
  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)const
{
  return _year == d._year
    && _month == d._month
    && _day == d._day;
}
// <运算符重载
bool Date::operator<(const Date& d)const
{
  return !(*this >= d);
}
// >=运算符重载
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);
}

③日期类+、-、+=、-=运算符重载

    在代码实现之前,我回顾一下 +、-、+=、-= 这些运算符运算结果有什么不同?


在定义了 int i = 1;那么i + 1;和i += 1;的含义是不同的;前者i的值并没有改变,后者i的值变成了2;


日期 += 天数:


       如果有个合法的日期,当需要计算100天后(假设)的日期时,当月的天数加满后就要给月进位,只要天数不合法,月就要进位,当月进位到13时,就给年进位,月份置1;


日期 + 天数:


       日期 += 天数改变了原来的日期,当你想要直到100天后的日期并且不改变当前日期时,就需要用 + ;通过实例化临时对象拷贝构造原来的日期,复用日期 += 天数的函数进行计算,既得到了100天后的日期,又不会对原来的日期进行改变;


日期 -= 天数 和 日期 - 天数,和上面的类似;


注意:


       1.如果使用+=时,给的天数是-100时,一定会存在错误;-100表面想要得到当前日期向前100天的日期;


       2.如果使用-=时,给的天数是-100时,一定会存在错误;-100表面想要得到当前日期向后100天的日期;


       对于以上两种情况,必须要加以判断


// 日期 += 天数
Date& Date::operator+=(int day)
{
  if (day < 0)
  {
    return *this -= -day;//如果传过来的天数是负数,实际上就是调用-=,把天数变为正数
  }
  _day += day;//先将天数加上
  while (_day > GetMonthDay(_year, _month))
  {
        //凑满本月天数,月进位1
    _day -= GetMonthDay(_year, _month);
    ++_month;
        //如果月进位到13时,年进位,月置1
    if (_month == 13)
    {
      _month = 1;
      _year++;
    }
  }
  return *this;
}
// 日期 + 天数
Date Date::operator+(int day)const
{
  Date ret(*this);
  //ret.operator+=(day);
  ret += day;
  return ret;
}
// 日期 -= 天数
Date& Date::operator-=(int day)
{
  if (day < 0)
  {
    return *this += -day;//如果传过来的天数是负数,实际上就是调用+=,把天数变为正数
  }
  _day -= day;//先将天数减去
  while (_day <= 0)
  {
        //向月借位
    --_month;
        //当月借完后,就要向年借位,并把月置1
    if (_month == 0)
    {
      --_year;
      _month = 12;
    }
        //加上当月的天数,直到天数符合条件
    _day += GetMonthDay(_year, _month);
  }
  return *this;
}
// 日期 - 天数
Date Date::operator-(int day)const
{
  Date ret(*this);
  ret -= day;
  return ret;
}

④日期类++、-- 重载

后置为了跟前置,进行区分,增加了一个int参数占位;跟前置,构成重载 ;


对于前置++和--而言,返回的是++或--之后的值;


对于后置++和--而言,返回的是++或--之前的值;


所以对于后置的操作,我们也需要临时的变量进行保存*this,改变*this后,返回临时的变量即可;

// 前置++
Date& Date::operator++()
{
  *this += 1;
  return *this;
}
// 后置++
Date Date::operator++(int)
{
  Date ret(*this);
  //Date ret = *this;
  *this += 1;
  return ret;
} 
// 前置--
Date& Date::operator--()
{
  *this -= 1;
  return *this;
}
// 后置--
Date Date::operator--(int)
{
  Date ret(*this);
  //Date ret = *this;
  *this -= 1;
  return ret;
}

一般更倾向于使用前置;后置比前置多了一些构造和析构操作;

⑤日期 - 日期及获取某天是周几

// 日期-日期 返回天数
int Date::operator-(const Date& d)
{
    //定义出大日期与小日期(假设)
  Date max = *this;
  Date min = d;
  int flag = 1;
    //先进行大小日期的判断,不符合则交换
  if (*this < d)
  {
    max = d;
    min = *this;
    flag = -1;// 这里flag的作用:如果是小日期-大日期,应该是负数
  }
  int count = 0;
  while (min != max)
  {
        //让小日期不断的累加,count记录天数
    ++min;
    ++count;
  }
  return count * flag;
}
//获取某天是周几
void Date::PrintWeekDay()const
{
  const char* arr[] = { "周一","周二", "周三", "周四", "周五", "周六", "周日" };
  /*Date start(1900, 1, 1);
  int count = *this - start;*/
  int count = *this - Date(1900, 1, 1);//匿名对象
  cout << arr[count % 7] << endl;
}

⑥对流插入和流提取的重载

对于上面的操作都是将日期给定好的,那么如何输入一个日期并输出出来呢?

1ecd1b2606ed46e9956a89f231c9802c.png

如果直接实例化出一个对象,按部就班的进行输入和输出,会发现出问题了;此时就需要流插入和流提取的重载

operator>>(); //流提取操作符重载
operator<<(); //流插入操作符重载

其实cout和cin是一个全局类型的对象,cout的类型是ostream、cin的类型是istream

按照刚才的那些运算符重载,这个也就可以定义为这样:

void operator<<(ostream& in);//定义
cin>>d1;//但是这里调不动
d1.operator<<(cin);//但是这里调用是没问题的
//上面的不就是:d1>>cin;

这种两种方式为什么存在差异呢?


       因为成员函数有隐含的this指针存在,那么cin>>d1;在传参时是把cin传给了this,d1传给了in,传参顺序传错了;对于这些运算符的函数重载,如果是双操作数的操作符重载,它是按照操作数的顺序进行传参的(即第一个参数是左操作数,第二个参数是右操作数);


       虽然d1>>cin可以实现,但是d1>>cin并不符合我们的使用习惯,所有这时候就不要将其重载为成员函数;可以将它定义为全局的,但是对于私有成员右访问不了了,这个时候,友元函数就派上用场了(友元函数会破话封装性,一般不建议使用);


       对于返回值还没有处理,刚才只能实现单次的输入输出,如果想要连续的输入和输出,那么返回类型cin和cout类类型(及cout的类型是ostream、cin的类型是istream);

//Date.h
class Date
{
  //友元函数
  friend ostream& operator<<(ostream& out, const Date& d);
  friend istream& operator>>(istream& in, Date& d);
public:
  //构造函数
  Date(int year = 1, int month = 1, int day = 1);
  /*
     ......
     ......
    */
  //void operator<<(ostream& out);//这里就不能实现成 成员函数
private:
  int _year;
  int _month;
  int _day;
};
//实现为全局的
ostream& operator<<(ostream& out, const Date& d);
istream& operator>>(istream& in, Date& d);
//Date.c
ostream& operator<<(ostream& out, const Date& d)
{
  out << d._year << "/" << d._month << "/" << d._day << endl;
  return out;
}
istream& operator>>(istream& in, Date& d)
{
  in >> d._year >> d._month >> d._day;
  return in;
}

六、const修饰类的成员函数

请思考一下几个问题:

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

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

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

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

通过下面的代码,做出解答

class Date
{
public:
  void Display()
  {
    cout << "Display ()" << endl;
    cout << "year:" << _year << endl;
    cout << "month:" << _month << endl;
    cout << "day:" << _day << endl << endl;
  }
  void Display() const
  {
    cout << "Display () 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;
  d1.Display();
  const Date d2;
  d2.Display();
}

1ecd1b2606ed46e9956a89f231c9802c.png

为了防止这些问题的发生,常常对成员函数进行const修饰,其本质是对*this的一个修饰;就是在成员函数的后面加上const;


对于非const修饰的对象可以调用const修饰的成员函数,反之不行;


对于非const成员函数内可以调用其它的const成员函数,反之不行;


但是也不是所有的成员函数都需要进行const的修饰,以上面的日期类来说,对于构造函数,是需要我们对其进行初始化的,必然存在值的修改,这种情况就不可以用const修饰;对于比较日期间的大小,并不存在值的改变,为了防止误操作,加上const会更好一些;

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

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

class Date
{ 
public :
     Date* operator&()
     {
         return this;
        //return nullptr;不允许获取对象的地址
     }
     const Date* operator&()const
     {
         return this;
     }
private :
     int _year ; // 年
     int _month ; // 月
     int _day ; // 日
};

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

目录
相关文章
|
1天前
|
存储 Java C++
【C++类和对象】探索static成员、友元以及内部类
【C++类和对象】探索static成员、友元以及内部类
|
1天前
|
安全 程序员 编译器
【C++类和对象】初始化列表与隐式类型转换
【C++类和对象】初始化列表与隐式类型转换
|
1天前
|
安全 编译器 C++
【C++类和对象】const成员函数及流插入提取
【C++类和对象】const成员函数及流插入提取
|
1天前
|
存储 C++
【C++类和对象】日期类的实现(下)
【C++类和对象】日期类的实现
|
8天前
|
存储 编译器 C++
c++的学习之路:6、类和对象(2)
c++的学习之路:6、类和对象(2)
22 0
|
8天前
|
存储 编译器 C语言
c++的学习之路:5、类和对象(1)
c++的学习之路:5、类和对象(1)
23 0
|
8天前
|
C++
c++的学习之路:7、类和对象(3)
c++的学习之路:7、类和对象(3)
21 0
|
1天前
|
编译器 C++
【C++类和对象】日期类的实现(上)
【C++类和对象】日期类的实现
|
1天前
|
编译器 C++ 索引
【C++类和对象】拷贝构造与赋值运算符重载(下)
【C++类和对象】拷贝构造与赋值运算符重载
|
1天前
|
存储 编译器 C++
【C++类和对象】拷贝构造与赋值运算符重载(上)
【C++类和对象】拷贝构造与赋值运算符重载