
👦个人主页:@Weraphael
✍🏻作者简介:目前学习C++和算法
✈️专栏:C++航路
🐋 希望大家多多支持,咱一起进步!😁
如果文章对你有帮助的话
欢迎 评论💬 点赞👍🏻 收藏 📂 加关注✨
目录
- 一、const成员
- 二、取地址及const取地址操作符重载
- 2.1 特殊使用情况
 
一、const成员
将
const修饰的“成员函数”称之为const成员函数,const修饰类成员函数,实际修饰该成员函数隐含的this指针,表明在该成员函数中不能对类的任何成员进行修改。
我们来看看下面的代码:
#include <iostream>
using namespace std;
class Date
{
public:
	Date(int year, int month, int day)
	{
		Year = year;
		Month = month;
		Day = day;
	}
	void Print(Date* const this)
	{
		cout << Year << "-" << Month << '-' << Day << endl;
	}
	
private:
	int Year; 
	int Month; 
	int Day; 
};
int main()
{
	Date d1(2023, 5, 20);
	d1.Print();
	const Date d2(2023, 5, 21);
	d2.Print();
	return 0;
}

- 以上代码对于
d2是编译不通过的,这是为什么呢?
- 当对象
d1调用成员函数this指针来访问该对象的成员变量和成员函数。this指针的类型:类名* const this,const修饰this,即成员函数中,不能修改this指针;- 而对于对象
d2,当调用成员函数时,编译器同样会自动将该对象作为第一个参数传递给成员函数,但不同的是,由于const修饰d2,因此this指针的类型应该是const Date* const this,因此不能给*this赋值,所以导致了报错。
因此,为了解决以上问题。C++是允许在函数后加上一个const,这样就能正常运行了:
#include <iostream>
using namespace std;
class Date
{
public:
	Date(int year, int month, int day)
	{
		Year = year;
		Month = month;
		Day = day;
	}
	void Print() const
	{
		cout << this->Year << "-" << this->Month << '-' << this->Day << endl;
	}
	
private:
	int Year; 
	int Month; 
	int Day; 
};
int main()
{
	Date d1(2023, 5, 20);
	d1.Print();
	const Date d2(2023, 5, 21);
	d2.Print();
	return 0;
}
【程序结果】

【总结】
- 成员函数在后加上
const后,普通和const修饰的对象都能用。- 但注意:由于
const修饰的对象,其形参中的*this被const修饰,也就说明不能对*this进行修改。因此,如果成员函数内要修改对象成员变量的函数千万不要用const修饰对象。- 如果声明和定义分离,声明的函数和定义的函数都要加
const
二、取地址及const取地址操作符重载
首先先来看看一下代码:
#include <iostream>
using namespace std;
class Date
{
public:
	Date(int year = 1, int month = 1, int day = 1)
	{
		Year = year;
		Month = month;
		Day = day;
	}
private:
	int Year; 
	int Month; 
	int Day; 
};
int main()
{
	Date d1(2023, 5, 20);
	const Date d2(2023, 5, 21);
	
	cout << &d1 << endl;
	cout << &d2 << endl;
	
	return 0;
}
【程序结果】

通过以上结果我们发现:
const取地址操作符重载不用重新定义,编译器默认会生成。
当然,如果想自己定义也是可以的,代码如下:
#include <iostream>
using namespace std;
class Date
{
public:
	Date(int year = 1, int month = 1, int day = 1)
	{
		Year = year;
		Month = month;
		Day = day;
	}
	
	Date* operator&()
	{
		return this;
	}
	
	const Date* operator&() const
	{
		return this;
	}
private:
	int Year; 
	int Month; 
	int Day; 
};
int main()
{
	Date d1(2023, 5, 20);
	const Date d2(2023, 5, 21);
	
	cout << &d1 << endl;
	cout << &d2 << endl;
	return 0;
}
【程序结果】

需要注意的是:重载
const取地址操作符时,返回的指针类型必须是const指针,否则会导致编译错误。
2.1 特殊使用情况
虽然这两个运算符一般不需要重载,使用编译器生成的默认取地址的重载即可,只有特殊情况,才需要重载,比如 不想让别人获取到指定的内容
#include <iostream>
using namespace std;
class Date
{
public:
	Date(int year = 1, int month = 1, int day = 1)
	{
		Year = year;
		Month = month;
		Day = day;
	}
	Date* operator&()
	{
		return nullptr;
	}
	const Date* operator&() const
	{
		return nullptr;
	}
private:
	int Year; 
	int Month; 
	int Day; 
};
int main()
{
	Date d1(2023, 5, 20);
	const Date d2(2023, 5, 21);
	cout << &d1 << endl;
	cout << &d2 << endl;
	return 0;
}
【程序结果】


















