C++ 日期类设计与 const 成员函数实践
const 成员函数与 this 指针
将 const 修饰的成员函数称为 const 成员函数。它实际修饰的是隐含的 this 指针,表明在该函数内不能修改类的任何成员变量。
原本 this 指针的类型是 类名* const this(指向对象的指针本身是常量)。当成员函数被 const 修饰后,this 的类型变为 const 类名* const this。这意味着不仅 this 指针本身不可变,它所指向的对象内容也不能被修改。
理解这一机制时,常遇到以下四个核心问题:
- const 对象可以调用非 const 成员函数吗? 不可以。权限不能放大,const 对象限制了成员修改能力。
- 非 const 对象可以调用 const 成员函数吗? 可以。权限可以缩小,普通对象调用只读函数是安全的。
- const 成员函数内可以调用其它的非 const 成员函数吗? 不可以。同样涉及权限放大的问题。
- 非 const 成员函数内可以调用其它的 const 成员函数吗? 可以。这是常见的组合使用场景。
日期类的默认成员函数
对于简单的数据类,编译器生成的默认行为通常足够用,但显式定义能更好地控制逻辑。以下是日期类的完整实现示例:
class Date {
public:
// 全缺省的构造函数
Date(int year = 1900, int month = 1, int day = 1) {
if (month > 0 && month < 13 && day > 0 && day <= GetMonthDay(year, month)) {
_year = year;
_month = month;
_day = day;
} else {
std::cout << "非法构造" << std::endl;
assert(0);
}
}
// 拷贝构造函数
Date(const Date& d) {
_year = d._year;
_month = d._month;
_day = d._day;
}
// 赋值运算符重载
Date& operator=(const Date& d) {
if ( != &d) {
_year = d._year;
_month = d._month;
_day = d._day;
}
*;
}
~() {
}
:
_year;
_month;
_day;
};


