【问题标题】:C++ - Conversion loses qualifiers error [duplicate]C ++ - 转换丢失限定符错误[重复]
【发布时间】:2018-05-04 17:33:54
【问题描述】:

我收到以下错误:

Conversion loses qualifiers

当尝试在不重复代码的情况下实现索引运算符时(我将展示代码段):

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);
}

但是,以下工作(这不使用辅助函数 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];
}

我真的需要两个索引函数吗(一个返回Point*,另一个返回const Point*)?

【问题讨论】:

标签: c++


【解决方案1】:

这是因为您从 const 函数中调用了非 const 函数。编译器会警告您,您的 const 对象在 temp 函数中将不再是 const

【讨论】:

  • 那么……他们真的需要两个函数吗?反正这个懒惰的重复不需要回答。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-10
  • 2012-09-25
  • 1970-01-01
  • 2014-02-07
  • 1970-01-01
相关资源
最近更新 更多