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

本文介绍了如何在C++中重载取地址运算符operator&,以及如何通过const修饰控制成员函数权限。类A中的默认成员函数和const版本的operator&函数展示了权限的缩小和平移。
摘要由CSDN通过智能技术生成

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

#include <iostream>
using namespace std;

class A
{
public:
	A(int year, int month, int day)
	{
		_year = year;
		_month = month;
		_day = day;
	}

	//它们是默认成员函数,我们不写编译器会自动生成,自动生成就够用了,所以一般是不需要我们自己写的。
	// 除非,对象的地址不想让别人取到。
	A* operator&()
	{
		return nullptr;
	}
	//上下两个函数需要同时写,因为返回值类型不同
	const A* operator&()const
	{
		return nullptr;
	}



	void Print()
	{
		cout << _year << "/" << _month << "/" << _day << endl;
	}
	// 上下两个函数构成函数重载(也可以只写一个)
	void Print()const
	{
		cout << _year << "/" << _month << "/" << _day << endl;
	}

private:
	int _year;
	int _month;
	int _day;

};

int main()
{
	A d1(2023, 8, 8);
	const A d2(2023, 9, 1);
	d1.Print();  //权限的缩小 A* --- const A*
	d2.Print();  //权限的平移 A* --- A*


	cout << &d1 << endl;
	cout << &d2 << endl;

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值