目录
1. const成员
将
const
修饰的
“
成员函数
”
称之为
const
成员函数
,
const
修饰类成员函数,实际修饰该成员函数
隐含的
this
指针
,表明在该成员函数中
不能对类的任何成员进行修改。
我们来看看下面的代码
class Date
{
public:
Date(int year, int month, int day)
{
_year = year;
_month = month;
_day = day;
}
void Print()
{
cout << "Print()" << endl;
cout << "year:" << _year << endl;
cout << "month:" << _month << endl;
cout << "day:" << _day << endl << endl;
}
void Print() const
{
cout << "Print()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(2022,1,13);
d1.Print();
const Date d2(2022,1,13);
d2.Print();
}
请思考下面的几个问题:
1. const
对象可以调用非
const
成员函数吗?
2.
非
const
对象可以调用
const
成员函数吗?
3. const
成员函数内可以调用其它的非
const
成员函数吗?
4.
非
const
成员函数内可以调用其它的
const
成员函数吗?
2. 取地址及const取地址操作符重载
这两个默认成员函数一般不用重新定义
,编译器默认会生成。
class Date
{
public :
Date* operator&()
{
return this ;
}
const Date* operator&()const
{
return this ;
}
private :
int _year ; // 年
int _month ; // 月
int _day ; // 日
};
这两个运算符一般不需要重载,使用编译器生成的默认取地址的重载即可,只有特殊情况,才需
要重载,比如
想让别人获取到指定的内容!