一、const成员函数
- 1.将const修饰的成员函数称之为const成员函数,const修饰成员函数放到成员函数参数列表的后⾯。
- 2.const实际修饰该成员函数隐含的this指针,表明在该成员函数中不能对类的任何成员进⾏修改。
在下面的日期类中,我们定义了print函数。但如果我们定义const修饰的Date对象时,是无法调用的,这是一种权限的放大。
#include<iostream>
using namespace std;
class Date
{
public:
Date(int year = 1, int month = 1, int day = 1)
{
_year = year;
_month = month;
_day = day;
}
// void Print(const Date* const this) const
void Print()
{
cout << _year << "-" << _month << "-" << _day << endl;
}
private:
int _year;
int _month;
int _day;
};
int main()
{
const Date d2(2024, 8, 5);
d2.Print();
return 0;
}
这里就需要用const修饰函数。const 修饰Date类的Print成员函数,Print隐含的this指针由 Date* const this 变为 const Date* const this
// void Print(const Date* const this) const
void Print() const
{
cout << _year << "-" << _month << "-" << _day << endl;
}
int main()
{
// 这⾥⾮const对象也可以调⽤const成员函数是⼀种权限的缩⼩
Date d1(2024, 7, 5);
d1.Print();
const Date d2(2024, 8, 5);
d2.Print();
return 0;
}
注:const修饰指向的内容和非const拷贝赋值时才涉及权限的放大和缩小
被const修饰的函数中,无法再去修改成员变量
二、取地址运算符重载
取地址运算符重载分为普通取地址运算符重载和const取地址运算符重载,⼀般这两个函数编译器⾃动⽣成
的就可以够我们⽤了,不需要去显⽰实现。除⾮⼀些很特殊的场景,⽐如我们不想让别⼈取到当前类对象的地址,就可以⾃⼰实现⼀份,胡乱返回⼀个地址。
class Date
{
public:
Date(int year = 1, int month = 1, int day = 1)
{
_year = year;
_month = month;
_day = day;
}
// void Print(const Date* const this) const
void Print() const
{
cout << _year << "-" << _month << "-" << _day << endl;
}
//取地址运算符重载
Date* operator&()
{
return this;
// return nullptr;
}
const Date* operator&()const
{
return this;
// return nullptr;
}
private:
int _year;
int _month;
int _day;
};
总结
其实取地址运算符重载是不太需要去关注的