class Date
{
public:
Date(unsigned int y, unsigned int m, unsigned int d);
Date(string yearMonthDay); // yearMonthDay must be in format "yyyy/mm/dd"
void setYear(unsigned int y);
void setMonth(unsigned int m);
void setDay(unsigned int d);
void setDate(unsigned int y, unsigned int m, unsigned int d);
unsigned int getYear() const;
unsigned int getMonth() const;
unsigned int getDay() const;
string getDate() const; // returns the date in format "yyyy/mm/dd"
void show() const; // shows the date on the screen in format "yyyy/mm/dd"
private:
unsigned int year;
unsigned int month;
unsigned int day;
};
Date
对象,但只有一个const引用,即const Date&
。仅允许您在该引用上调用const方法。这些方法以其签名保证不会更改Date
对象(并且编译器也不允许这样做)。 mutable
成员是一个例外。签名前面的A const
关键字与return参数有关。因此,例如,const std::string& getName() const;
返回对字符串的const引用。它本身就是const,因为它不会更改对象。这是签名前后的const
的两种含义。