lesson2(补充)取地址及const取地址操作符重载

个人主页:Lei宝啊

愿所有美好如期而遇


以下两个默认成员函数一般不用重新定义 ,编译器默认会生成。

复制代码
#include <iostream>
using namespace std;

class Date
{

public:

	Date()
		:_year(2023)
		,_month(10)
		,_day(28)
	{}

	Date* operator&()
	{
		return this;
	}

	const Date* operator&() const
	{
		return this;
	}

private:
	int _year;
	int _month;
	int _day;
};

int main()
{

	Date a;
	cout << &a << endl;

	const Date b;
	cout << &b << endl;

	return 0;
}


这两个运算符一般不需要重载,使用编译器生成的默认取地址的重载即可,只有特殊情况,才需
要重载,比如 想让别人获取到指定的内容!

复制代码
#include <iostream>
using namespace std;

class Date
{

public:

	Date()
		:_year(2023)
		,_month(10)
		,_day(28)
	{}

	Date* operator&()
	{
		return nullptr;
	}

	const Date* operator&() const
	{
		return this;
	}

private:
	int _year;
	int _month;
	int _day;
};

int main()
{

	Date a;
	cout << &a << endl;

	const Date b;
	cout << &b << endl;

	return 0;
}

甚至我们可以返回一个错误的地址(滑稽)

相关推荐
阿波茨的鹅1 小时前
VSCode C++ 项目配置教程
c++·ide·vscode
程序员与背包客_CoderZ1 小时前
C/C++版LLM推理框架Llama.cpp——入门与编码实战
c语言·开发语言·网络·c++·人工智能·语言模型·llama
喵了几个咪2 小时前
C++ IDE:最适合 C++ 初学者的 IDE 是什么?
开发语言·c++·ide
2501_941802482 小时前
C++高性能并发编程实战:从多线程管理到内存优化与任务调度全流程解析
java·开发语言·c++
zzzsde2 小时前
【C++】哈希表实现
数据结构·c++·哈希算法·散列表
Elias不吃糖3 小时前
C++ 中“编译器自动帮我传参”和“我自己写初始化”的本质区别
c++
阿巴~阿巴~3 小时前
TCP服务器实现全流程解析(简易回声服务端):从套接字创建到请求处理
linux·服务器·网络·c++·tcp·socket网络编程
Elias不吃糖3 小时前
LeetCode每日一练(189, 122)
c++·算法·leetcode
赖small强3 小时前
【Linux C/C++开发】第20章:进程间通信理论
linux·c语言·c++·进程间通信
赖small强3 小时前
【Linux C/C++开发】第24章:现代C++特性(C++17/20)核心概念
linux·c语言·c++·c++17/20