目录
7.const成员
将const修饰的“成员函数”称之为const成员函数,const修饰类成员函数,实际修饰该成员函数隐含的this指针,表明在该成员函数中不能对类的任何成员进行修改。
编译器堆const成员函数的处理:
我们来看看下面的代码
#include<iostream>
using namespace std;
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();
}
int main()
{
Test();
return 0;
}
请思考下面的几个问题:
1. const
对象可以调用非
const
成员函数吗?
2.
非
const
对象可以调用
const
成员函数吗?
3. const
成员函数内可以调用其它的非
const
成员函数吗?
4.
非
const
成员函数内可以调用其它的
const
成员函数吗?
解答:
1.不可以,因为const对象调用非const成员函数时,对象的
权限被放大了
2.可以 权限缩小
3.不可以,因为const成员函数调用其他的非const成员函数时,函数中对象的
权限被放大了
4.可以,权限缩小
总结一下:
1.成员函数,如果是一个 对成员变量只进行读访问的 函数 ->建议加const 这样const对象和 非const对象都可以使用
2.成员函数,如果是一个 对成员变量要进行读写访问的 函数 ->不能加const,否则不能修改成员变量
8.取地址及const取地址操作符重载
这两个默认成员函数一般不用重新定义
,编译器默认会生成。
class Date
{
public:
Date* operator&()
{
return this;
}
const Date* operator&()const
{
return this;
}
private:
int _year; // 年
int _month; // 月
int _day; // 日
};
这两个运算符一般不需要重载,使用编译器生成的默认取地址的重载即可,只有特殊情况,才需
要重载,比如不想
让别人获取到指定的内容!