目录
Ⅰ. 引入
本篇我们用C++来实现一个日期计算器。
想知道迄今为止你在地球上一共度过了多少天吗?距离寒假还有多少天呢?一百天后会是几月几号呢?
解开这些问题的答案,只需来写一个日期计算器~👻
日期计算器是C++入门以来的第一个小项目,亲自实践一遍,我们在C++上的经验值将⬆️⬆️⬆️

🚩我们将分三步:
Step1:在头文件中把日期类的大体轮廓列出来
Step2:把声明的功能一一实现
Step3:逐个测试。我们写一点,测一点。
这样,就可顺利把日期计算器写出个七七八八。
在遇到较复杂的算法时,我会提供思路。
至于某些锦上添花的功能,我们后续想到了,再添上去。
Ⅱ. 列轮廓
🤔我们先来定义一个日期类,同时看看要实现哪些功能:
#pragma once
#include<iostream>
using namespace std;
class Date {
public:
Date(int year = 1900, int month = 1, int day = 1); //构造函数:用于初始化
void Print(); //打印日期,便于测试
//功能的具体实现
bool operator==(const Date& d); //判断俩date是否相等
bool operator!=(const Date& d);
bool operator>(const Date& d); //date间比较大小
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的自增/自减
Date operatoe++(int);
Date& operator--();
Date operatoe--(int);
int operator-(const Date& d); //算两个date间差多少天
private:
int _year;
int _month;
int _day;
};
Ⅲ. 功能的实现
构造函数
➡️我们实现一个全缺省的构造函数:
class Date{
public:
Date(int year = 1900, int month = 1, int day = 1) {
_year = year;
_month = month;
_day = day;
}
private:
int _year;
int _month;
int _day;
}
每次实例化出一个对象,都要调用构造函数,调用频率非常高。
所以,我们干脆就把这短短的几行定义在类里,做内联函数。
❓你可能会疑惑:为啥_year可以直接拿来用,不需要this->year嘛?
后者当然可以写,但没必要。因为我们在使用类的成员函数or成员变量时,this指针会默认加上的。
我们就不用一一手动加啦✌
➡️Print,写在Date.c里:
void Date::Print() {
printf("%d-%d-%d\n", _year, _month, _day);
}
❓为啥要加Date::呢?
要知道,类定义了一个全新的作用域。类里类外,是有一层屏障的。
正因为类域的存在,我们不能直接从外部访问类的成员。
因此,把成员函数拿到类外定义时,要指明作用域,即加上Date::
❓我们不是学了cout嘛,为啥不直接cout输出,还得用printf?
这个问题我们先保留着,下一趴再讲。🤪
🔬🧪这俩函数先测试一波:
void Test1() {
Date d1(2023, 8, 23);
Date d2;
d1.Print();
d2.Print();
}
int main()
{
Test1();
return 0;
}
结果:

判断是否相等 == | !=
➡️==:
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);
}
有没有发现,其实我们只实现了==,
写!=时直接套用了==的功能,这叫做复用。
复用可以减少工作量,提高代码的重用性。
❓为啥只有一个形参?
其实有两个形参:第一个形参是隐形的:this指针。只有第二个形参可见。
“d1!=d2; ” 就相当于在调用函数 “d1.operator!=(d2); ”
此函数的this指针指向d1,形参的d即d2。
🔬🧪测试一下:
void Test2() {
Date d1(2023, 8, 23);
Date d2(2000, 1, 1);
if (d1 != d2) {
cout << "unequal"<<endl;
}
}
int main()
{
//Test1();
Test2();
return 0;
}
结果:

判断大小 > | >= | < | <=
日期的大小,听着蛮抽象。其实就是日期的先后:2023年1月1日比2000年1月1日要大(后)。
➡️>:
bool


3880

被折叠的 条评论
为什么被折叠?



