返回数组元素时非const引用的无效初始化 [英] invalid initialization of non-const reference when returning an array element

查看:153
本文介绍了返回数组元素时非const引用的无效初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在写一个包装动态分配的数组的类,我试图写operator []函数。目前我有:

  bool&解决方案:: operator [](unsigned int pos)
{
if(pos <_size)
{
return this-> _data [pos];
}
else
{
return false;
}
}

但我从g ++得到以下错误: p>

错误:从类型'bool'的右值初始化类型'bool&'的非const引用 / p>

我应该怎么做?我需要[]运算符才能修改元素。

解决方案

它是因为布尔文字 false 这是一个右值,不能绑定到运算符[]的返回类型的非const引用 bool&



只需将返回类型从 bool& 更改为 bool ,错误将消失。但这不会解决你的问题,如你所说,你想返回引用的元素,以便可以在callsite上更改元素,那么你应该这样:

  //正确的解决方案
bool&解决方案:: operator [](unsigned int pos)
{
if(pos> _size)
throw std :: out_of_range(invalid index);
return this-> _data [pos];
}

也就是说,您应该通知调用者无效的索引,可以知道出了问题。 C ++各种异常类正好用于此目的,即通知错误。



索引无效时尝试返回任何值(false或true),只是隐藏问题。问自己,如果你返回一个 dummy 布尔值(你存储在类中),那么调用者知道索引是否无效?

  //不正确的解决方案
bool&解决方案:: operator [](unsigned int pos)
{
if(pos> _size)
return _dummy; //它隐藏的问题,无论是真的还是假的!
return this-> _data [pos];
}


I'm writing a class that wraps a dynamically allocated array and I'm trying to write the operator[] function. Currently I have:

bool& solution::operator[](unsigned int pos)
{
  if(pos < _size)
  {
    return this->_data[pos];
  }
  else
  {
    return false;
  }
}

But I get the following error from g++:

error: invalid initialization of non-const reference of type ‘bool&’ from an rvalue of type ‘bool’

How should I be doing this? I need the [] operator to be able to modify elements.

解决方案

Its because the boolean literalfalse which is a rvalue, cannot be bound to non-const reference bool& which is the return type of operator[].

Simply change the return type from bool& to bool, the error will disappear. But that isn't going to solve your problem, as you said,you want to return reference of the element, so that the element can be changed on the callsite, then you've to something like this:

//correct solution
bool& solution::operator[](unsigned int pos)
{
  if(pos > _size)
     throw std::out_of_range("invalid index");
  return this->_data[pos];
}

That is, you should notify the caller of an invalid index, so that it can know that something went wrong. C++ various exception classes are there exactly for that purpose, i.e to notify error.

Attempting to return any value (false or true) when the index is invalid, simply hides the problem. Ask yourself, if you return a dummy boolean value (which you store in the class), then would the caller know if the index was invalid? No.

//incorrect solution
bool& solution::operator[](unsigned int pos)
{
  if(pos > _size)
     return _dummy; //it hides the problem, no matter if its true or false!
  return this->_data[pos];
}

这篇关于返回数组元素时非const引用的无效初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆