const成员、取地址及取地址操作符重载
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();
}
思考以下问题
- const对象可以调用非const成员函数吗?
不可以。
会报错,错误 C2662 “void Date::Print(void)”: 不能将“this”指针从“const Date”转换为“Date &” 。
但是非const对象可以调用const成员函数,这也就是前文所说的"权限可以缩小不可以放大"。 - 非const对象可以调用const成员函数吗?
可以。 - const成员函数内可以调用其它的非const成员函数吗?
当然可以,但是要注意的是:在你调用的非const成员函数中不可以修改this指针下的成员变量,也就是不可以对对象进行修改,遵循const成员函数的约定即可。 - 非const成员函数内可以调用其它的const成员函数吗?
可以。非const函数对于成员变量是没有限制的,所以在非const函数中调用const函数是没有问题的。
取地址及const取地址操作符重载
这两个默认成员函数一般不用重新定义 ,编译器默认会生成。
class Date
{
public:
Date* operator&()
{
return this;
}
const Date* operator&()const
{
return this;
}
private:
int _year; // 年
int _month; // 月
int _day; // 日
};
这两个运算符一般不需要重载,使用编译器生成的默认取地址的重载即可,只有特殊情况,才需要重载,比如想让别人获取到指定的内容!