首页 > 解决方案 > 类型 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");
}
...

标签: c++functionconstantsref

解决方案


constinT const &表示此方法返回对 T 的常量引用。 constin 参数表示索引参数是常量。 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


推荐阅读