目录
1. const成员函数的使用引入
const 修饰的“成员函数”称之为const成员函数,const修饰类成员函数,实际修饰该成员函数隐含的this 指针,表明在该成员函数中不能对类的任何成员进行修改 。我们来看下面的代码:
#include<iostream>
using namespace std;
class Date
{
public:
Date(int year = 2024, int month = 3, int day = 16)//构造函数
{
_year = year;
_month = month;
_day = day;
}
void print()
{
cout << _year << " " << _month << " " << _day << endl;
}
private:
int _year;
int _month;
int _day;
};
void f1(const Date& d)
{
d.print();
}
int main()
{
Date d1;
d1.print();
Date d2;
f1(d2);
return 0;
}
我们将代码运行起来发现第28行出现了报错,这是什么原因呢?
为了解决这个问题,我们首先要详细回顾一下 this 指针的含义,this指针本质上是一个隐含的形参。实际上我们定义的日期类中的成员函数会变成这种函数形式:
void print(Data* const this) //注意const修饰,指针不能修改,指向的内容可以修改
{
cout << _year << " " << _month << " " << _day << endl;
}
也就是说,谁调用就把谁的地址传过来,此时的this就是形参,整个过程就叫做隐含的this指针。this指针本身不能修改,因为它是const修饰的,但是this指针指向的对象可以被修改。
我们可以对 this 指针做出以下的总结:
this指针的类型:类的类型* const,只能在“成员函数”的内部使用
this指针本质上其实是一个成员函数的形参,是对象调用成员函数时,将对象地址作为实参传递给this形参。所以对象中不存储this指针。
this指针是成员函数第一个隐含的指针形参,一般情况由编译器通过ecx寄存器自动传递,不需要用户传递。
因此我们对于上面的报错代码可以做出以下分析,从而得到程序报错的原因。如图所示:
Date*传给Date* const没有问题,都是可读也可修改,所以d1调用print()不会出错,const Date* 指向的内容不能被修改,可是当它传给Date*时就出错了,因为Date*是可以修改的,这里传过去会导致权限放大。所以当然d调用print()函数报错。权限不能放大,只能缩小或不变。
因此,我们只需要在函数后面加上 const 修饰即可。
void print() const //void print(const Date* const this)
{
cout << _year << " " << _month << " " << _day << endl;
}
2. const 成员函数使用的另一个例子
先看代码:
class Date
{
public:
Date(int year = 2024, int month = 3, int day = 16)//构造函数
{
_year = year;
_month = month;
_day = day;
}
void print() const //void print(Date* const this)
{
cout << _year << " " << _month << " " << _day << endl;
}
bool operator<(const Date& d)
{
if (_year < d._year ||
_year == d._year && _month < d._month ||
_year == d._year && _month == d._month && _day < d._day)
{
return true;
}
else
{
return false;
}
}
private:
int _year;
int _month;
int _day;
};
void f1(const Date& d)
{
d.print();//d.print(&d)
}
int main()
{
Date d1(2025,5,20);
const Date d2(2025, 5, 21);
d1 < d2;
d2 < d1;
return 0;
}
毫无疑问,这样的程序依然会发生报错,我们可以提前推断出程序错误的原因可能是发生了权限不匹配问题。
现在我们来做分析: &d1: Date* &d2: const Date*
同样的我们可以对隐藏的this指针加上const修饰,做到权限保持。
bool operator<(const Date& d) const
3. const 成员函数使用总结
const 对象不可以调用非 const 成员函数。const对象去调用非const成员函数,会造成权限放大的现象,原本在类外const对象的内容是不可以修改的,但是到了函数内部却有可以修改了,这是不被允许的。
非const 对象可以调用 const 成员函数。非const对象本身就是可读可写的,那在函数内部你要去修改或者不修改都不会有影响。
const成员函数内不可以调用其它的非const成员函数。 const成员函数内部只能调用const成员函数。因为const成员函数内部的this指针已经具有常属性的,万一这个非const成员函数去修改了成员变量的内容就会出问题了。
非const成员函数内可以调用其它的const成员函数。权限缩小是允许的。