在成员函数后面加const,const修饰this指针所指向的对象,也就是保证调用这个const成员函数的对象在函数内不会被改变。
Like This:
#include<iostream>
using namespace std;
class Date
{
public:
Date(int year,int month,int day)
:_year(year)
,_montf(month)
,_day(day)
{}
void Print() const
{
cout<<"year:" <<_year<< endl;
cout<<"month:" <<_month<< endl;
cout<<"day:" <<_day<< endl<<endl ;
cout<<"Print()"<<endl;
}
private:
int _year;
int _month;
int _day;
};
int main()
{
const Date d1;
d1.Display ();
return 0;
}
这样调用的对象的值将不会改变,将Print调用的对象的私有值属性变为只读属性