我正在编写一个包装动态分配数组的类,并且正在尝试编写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’
我应该怎么做?我需要 [] 运算符才能修改元素。
这是因为布尔文字false
这是一个右值,不能绑定到非常量引用bool&
这是的返回类型operator[]
.
只需更改返回类型bool&
to bool
,错误就会消失。但这并不能解决你的问题,正如你所说,你想返回参考元素的,以便可以在调用站点上更改元素,然后您必须这样做:
//correct solution
bool& solution::operator[](unsigned int pos)
{
if(pos > _size)
throw std::out_of_range("invalid index");
return this->_data[pos];
}
也就是说,您应该通知调用者无效的索引,以便它知道出了问题。 C++各种异常类是否正是为了这个目的,即通知错误。
当索引无效时尝试返回任何值(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];
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)