c++ - 类型 const ref 函数 const?
问题描述
我对 const 这里的 2 次出现感到有些困惑,这是什么意思?
这种格式可以应用于其他对象吗?
...
T const & GetAt(size_t const index) const
{
if (index < Size) return data[index];
throw std::out_of_range("index out of range");
}
...
解决方案
const
inT const &
表示此方法返回对 T 的常量引用。
const
in 参数表示索引参数是常量。
const
在参数列表之后意味着可以在常量对象或常量引用/指向对象的指针上调用该方法,即:
const YourClass obj;
YourClass const & cref = obj.
obj.GetAt(10);// no compile error.
cref.GetAt(10);// no compile error either.
如果方法不是常量,那么在常量对象/引用/指针上调用它会导致编译错误。
有关const
阅读本文的其他用法https://en.cppreference.com/book/intro/const
推荐阅读
- python - 自动更正功能错误:字符串 2 列表
- shopify - 我可以在 shopify 的收藏列表中创建收藏列表吗?是否可以
- python - 分析从 Python 代码调用的 C++ OpenCV 函数
- php - 表单提交时未调用php操作文件
- sql - 从 Microsoft SQL Server 表中删除某个日期之前的所有记录
- python - 从类元素中创建一个 python 列表的副本
- java - 无法在 try/catch 块中捕获“UnreachableBrowserException”
- python - 删除变量(指针)值不会删除它指向的值
- c - 使用 Clickone 发布后无法运行应用程序
- rest - 如何在我的流星应用程序的两个不同包中拥有具有相同 URL 的两条不同路由?