当前位置: 首页 > news >正文

C++入门——类的默认成员函数(取地址运算符重载)

文章目录

  • 一、const成员函数
  • 二、取地址运算符重载
  • 总结


一、const成员函数

  • 1.将const修饰的成员函数称之为const成员函数,const修饰成员函数放到成员函数参数列表的后⾯。
  • 2.const实际修饰该成员函数隐含的this指针,表明在该成员函数中不能对类的任何成员进⾏修改。
    在下面的日期类中,我们定义了print函数。但如果我们定义const修饰的Date对象时,是无法调用的,这是一种权限的放大。
    在这里插入图片描述
#include<iostream>
using namespace std;
class Date
{
public:Date(int year = 1, int month = 1, int day = 1){_year = year;_month = month;_day = day;}// void Print(const Date* const this) constvoid Print(){cout << _year << "-" << _month << "-" << _day << endl;}
private:int _year;int _month;int _day;
};
int main()
{const Date d2(2024, 8, 5);d2.Print();return 0;
}

这里就需要用const修饰函数。const 修饰Date类的Print成员函数,Print隐含的this指针由 Date* const this 变为 const Date* const this

	// void Print(const Date* const this) constvoid Print() const{cout << _year << "-" << _month << "-" << _day << endl;}int main()
{// 这⾥⾮const对象也可以调⽤const成员函数是⼀种权限的缩⼩Date d1(2024, 7, 5);d1.Print();const Date d2(2024, 8, 5);d2.Print();return 0;
}

注:const修饰指向的内容和非const拷贝赋值时才涉及权限的放大和缩小
被const修饰的函数中,无法再去修改成员变量

二、取地址运算符重载

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

class Date
{
public:Date(int year = 1, int month = 1, int day = 1){_year = year;_month = month;_day = day;}// void Print(const Date* const this) constvoid Print() const{cout << _year << "-" << _month << "-" << _day << endl;}//取地址运算符重载Date* operator&(){return this;// return nullptr;}const Date* operator&()const{return this;// return nullptr;}private:int _year;int _month;int _day;
};

总结

其实取地址运算符重载是不太需要去关注的

http://www.lryc.cn/news/454845.html

相关文章:

  • 学习记录:js算法(四十九):二叉树的层序遍历
  • 【PCB工艺】表面贴装技术中常见错误
  • 3.使用条件语句编写存储过程(3/10)
  • Effective C++中文版学习记录(三)
  • VBA学习(76):文件合并神器/代码
  • 非农就业数据超预期,美联储降息步伐或放缓?
  • 每日OJ题_牛客_乒乓球筐_哈希_C++_Java
  • 基于SpringBoot+Vue的酒店客房管理系统
  • 检索增强思考 RAT(RAG+COT):提升 AI 推理能力的强大组合
  • python脚本实现Redis未授权访问漏洞利用
  • 简单线性回归分析-基于R语言
  • 上海理工大学《2023年+2019年867自动控制原理真题》 (完整版)
  • 计算机网络面试题——第三篇
  • Elasticsearch 开放推理 API 增加了对 Google AI Studio 的支持
  • react-问卷星项目(7)
  • 【git】main|REBASE 2/6
  • 51单片机的水质检测系统【proteus仿真+程序+报告+原理图+演示视频】
  • 【python面试宝典7】线程池,模块和包
  • Android input系统原理二
  • Oracle登录报错-ORA-01017: invalid username/password;logon denied
  • JavaScript 获取浏览器本地数据的4种方式
  • 77寸OLED透明触摸屏有哪些应用场景
  • 二分解题的奇技淫巧都有哪些,你还不会吗?
  • LeetCode-871 最低加油次数
  • OpenCV-OCR
  • Linux卸载mysql
  • 【大语言模型-论文精读】用于医疗领域摘要任务的大型语言模型评估综述
  • 图吧工具箱
  • vue2 + View design 使用inputNumber设置默认值为undefined但展示数据为1且表单校验不通过的原因
  • 【SpringSecurity】基本流程