我正在编写一个包装动态分配数组的类,我正在尝试编写operator []函数。目前我有:
bool& solution::operator[](unsigned int pos)
{
if(pos < _size)
{
return this->_data[pos];
}
else
{
return false;
}
}
但是我从g ++中得到以下错误:
error: invalid initialization of non-const reference of type ‘bool&’ from an rvalue of type ‘bool’
我该怎么做?我需要[]运算符才能修改元素。
答案 0 :(得分:8)
因为作为右值的布尔文字false
不能绑定到非const引用bool&
,它是operator[]
的返回类型。
只需将返回类型从bool&
更改为bool
,错误就会消失。但这并不能解决你的问题,就像你说的那样,你想要返回元素的引用,以便可以在调用点上更改元素,然后你就可以这样做了:
//correct solution
bool& solution::operator[](unsigned int pos)
{
if(pos > _size)
throw std::out_of_range("invalid index");
return this->_data[pos];
}
也就是说,您应该通知调用者无效索引,以便它可以知道出错了。 C ++各种exception classes正是出于这个目的,即通知错误。
在索引无效时尝试返回任何值(false或true),只需隐藏问题。问问自己,如果你返回一个 dummy 布尔值(你存储在类中),那么调用者是否知道索引是否无效?否。
//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];
}