c++ - C++ 中的括号重载运算符是否应该声明为 const 函数?
问题描述
我想在 C++ 中为我的自定义 Array 类实现一个括号 [] 运算符。我有几个选择:
(1) Point& operator[](int index)
(2) Point& operator[](int index) const
(3)const Point& operator[](int index) const
(3) 如果用户声明一个 const 对象,我理解是必需的。但是,对于一般情况 (1, 2),我应该将函数设为 const,因为该对象从未在函数体中被修改过吗?
解决方案
(1) 返回引用是正确的。
(2) 需要是非的const
,因为您希望能够通过返回的引用来修改类成员。
(3) 需要const
如此[]
才能调用上一个const this
或等效的引用。
写入Point& operator[](int index) const
会导致意外行为,因为您可以通过引用修改类成员。您的Point& operator[](int index)
函数代码可能不会修改对象,但它允许其他代码修改对象,因为它返回对数据成员的非常量引用。所以Point& operator[](int index) const
不是你可以提供的,编译器不应该接受提供对类数据成员的非常量访问的 const 函数。
相反,您应该提供一个非常量版本和一个 const 重载:
Point& operator[](int index);
const Point& operator[](int index) const;
推荐阅读
- python - 调用 Python 对象时,Python 2.7 中的 Jira 超出了最大递归深度
- spring - ftl @spring.message - 处理 NoSuchMessageException
- php - $_SESSION 变量在设置时总是打印'S'而不是预期的变量
- python - 函数逐字母呈现元素而不是字符串
- r - 使用错误消息确定操作过程
- android - 如何使用android管理api管理个人资料?
- c# - 被碰撞体击中时将对象捕捉到位置
- dictionary - 如何将图像和文本添加到传单地图的弹出窗口
- c# - 使用 dll 文件运行网站时,asp.net 核心身份登录不起作用
- sql-server - oracle时间戳6转换为sql server datetime2错误