类和对象:取地址运算符重载

1.const成员函数

• 将const修饰的成员函数称之为const成员函数,const修饰成员函数放到成员函数参数列表的后⾯;
• const实际修饰该成员函数隐含的this指针,表明在该成员函数中不能对类的任何成员进⾏修改。 const 修饰Date类的Print成员函数,Print隐含的this指针由 Date* const this 变为 const
Date* const this

void Date::Print()
{
	cout << _year << "-" << _month << "-" << _day << endl;
}
 
const Date d1(2024, 7, 19);
d1.Print();
//权限放大

 

解决:(const修饰后不能修改)

void Date::Print() const
{
	cout << _year << "-" << _month << "-" << _day << endl;
}
 
const Date d1(2024, 7, 19);
d1.Print();
Date d2(2024, 7, 20);
d2.Print();
//权限可以缩小

 所以:以后不修改的尽量加上const

2.取地址运算符重载

取地址运算符重载分为普通取地址运算符重载和const取地址运算符重载,⼀般这两个函数编译器⾃动 ⽣成的就可以够我们⽤了,不需要去显⽰实现。除⾮⼀些很特殊的场景,⽐如我们不想让别⼈取到当前类对象的地址,就可以⾃⼰实现⼀份,胡乱返回⼀个地址

#include<iostream>
using namespace std;
 
class Date
{
public:
//两个都写,优先取合适的
	Date* operator&()
	{
		return this;
		// return nullptr;
 
		//使坏:
		//return (Date*)0x2673FF40;
	}
	const Date* operator&()const
	{
		return this;
		// return nullptr;
		//return (Date*)0x2673FF40;
	}
private:
	int _year; // 年
	int _month; // ⽉
	int _day; // ⽇
};

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值