【问题标题】:type const ref function const?类型 const ref 函数 const?
【发布时间】:2021-12-13 14:30:50
【问题描述】:
所以我对 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");
}
...
非常感谢任何愿意为我阐明这一点的人。
【问题讨论】:
标签:
c++
function
constants
ref
【解决方案1】:
T const & -> 返回 T 类型的 const 引用,表示您可以从该函数外部访问的引用,但 const 表示您不能修改它.
(size_t const index) -> 参数index 是const,不能在函数内部修改
GetAt(size_t const index) const -> 方法GetAt 不能修改类中的任何成员,也不能调用非const 限定方法。
可以说它不会修改类的状态。
【解决方案2】:
const in T const & 表示此方法返回对 T 的常量引用。
参数中的const 表示索引参数是常数。
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