T& f() { // some code ... }
const T& f() const { // some code ... }
Run Code Online (Sandbox Code Playgroud)
我现在已经看过几次了(在我迄今为止研究的介绍性书中).我知道第一个const使返回值为const,换句话说:不可修改.我相信第二个const允许为const声明的变量调用该函数.
但是为什么你会在同一个类定义中同时拥有这两个函数?编译器如何区分这些?我相信第二个f()(带const)也可以调用非const变量.
我收到以下错误:
Conversion loses qualifiers
Run Code Online (Sandbox Code Playgroud)
尝试在没有代码重复的情况下实现索引运算符时(我将显示代码段):
Point* BufferedList::indexTemp(size_t idx)
{
if (idx >= size) return nullptr;
return &arr[idx];
}
const Point* BufferedList::operator [](size_t idx) const
{
return indexTemp(idx);
}
Point* BufferedList::operator [](size_t idx)
{
return indexTemp(idx);
}
Run Code Online (Sandbox Code Playgroud)
但是,以下有效(这不使用辅助函数indexTemp,它是代码重复):
const Point* BufferedList::operator [](size_t idx) const
{
if (idx >= size) return nullptr;
return &arr[idx];
}
Point* BufferedList::operator [](size_t idx)
{
if (idx >= size) return nullptr;
return &arr[idx];
}
Run Code Online (Sandbox Code Playgroud)
我真的需要两个用于索引的函数(一个返回Point*,另一个返回const Point*)?