取地址及const取地址重载 (不常用)

126 阅读2分钟

「这是我参与2022首次更文挑战的第22天,活动详情查看:2022首次更文挑战

💦 const修饰类的成员函数

class Date
{
public:
	Date(int year = 0, int month = 1, int day = 1)
	{
		_year = year;
		_month = month;
		_day = day;
	}
	void Print1()//void Print(Date* this)
	{
		cout << _year << "/" << _month << "/" << _day << endl;
	}
	void Print2() const//void Print(const Date* this)
	{
		cout << _year << "/" << _month << "/" << _day << endl;
	}
private:
	int _year;
	int _month;
	int _day;
};
int main()
{
	Date d1(2021, 10, 13);
	//Date d2(2021, 10, 14);//ok
	//const Date d2(2021, 10, 14);//err
	d1.Print1();
	d2.Print1();//d2.Print(&d2);

	const Date d3(2021, 10, 14);//ok
	d3.Print2();//d3.Print(&d3);

	return 0;
}

📝 说明

为什么const对象不能调用Print ❓ 在这里插入图片描述 我们之前说了在调用类成员函数时有一个隐式的参数 this 指针 在这里插入图片描述 💨总结

1、成员函数加 const,变成 const 成员函数是有好处的,这样 const 对象可以调用,非 const 对象也可以调用。

2、不是说所有的成员函数都要加 const ,具体要看成员函数的功能,如果成员函数是修改型 (operrato+=、Push),那就不能加;如果是只读型 (Print、operator+),那就最好加。

3、const 对象不可以调用非 const 成员函数 (权限放大);非 const 对象可以调用 const 成员函数 (权限缩小)。

4、const 成员函数内不可以调用其它非 const 成员函数;非 const 成员函数内可以调用其它 const 成员函数。

💦 取地址及const取地址操作符重载

class Date
{
public:
	Date(int year = 0, int month = 1, int day = 1)
	{
		_year = year;
		_month = month;
		_day = day;
	}
	//普通对象取地址 
	/*Date* operator&()
	{
		return this;
	}*/
	//const对象取地址 
	/*const Date* operator&() const
	{
		return this;
	}*/

	Date* operator&()
	{
		return nullptr;
	}
	const Date* operator&() const
	{
		return nullptr;	
	}
	
private:
	int _year;
	int _month;
	int _day;
};
int main()
{
	Date d1(2021, 10, 13);
	const Date d2(2021, 10, 14);

	cout << &d1 << endl;
	cout << &d2 << endl;
	return 0;
}

📝 说明

一般不需要写,编译器生成的就够用。

如果非要写,比如不想让别人获取对象的地址,就可以自己实现,返回 nullptr。