我正在编写一个包装动态分配数组的类,我正在尝试编写operator []函数.目前我有:
bool& solution::operator[](unsigned int pos)
{
if(pos < _size)
{
return this->_data[pos];
}
else
{
return false;
}
}
Run Code Online (Sandbox Code Playgroud)
但是我从g ++中得到以下错误:
error: invalid initialization of non-const reference of type ‘bool&’ from an rvalue of type ‘bool’
我该怎么做?我需要[]运算符才能修改元素.
因为boolean文字false是一个rvalue,不能绑定到非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];
}
Run Code Online (Sandbox Code Playgroud)
也就是说,您应该通知调用者无效索引,以便它可以知道出错了.C++各种异常类正是为了这个目的,即通知错误.
尝试在索引无效时返回任何值(false或true),只需隐藏问题.问问自己,如果你返回一个虚拟布尔值(你存储在类中),那么调用者是否知道索引是否无效?没有.
//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];
}
Run Code Online (Sandbox Code Playgroud)