![](/img/trans.png)
[英]Strange “invalid initialization of non-const reference” when using templates
[英]invalid initialization of non-const reference when returning an array element
我正在編寫一個包裝動態分配的數組的類,並嘗試編寫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&
更改為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),只會隱藏問題。 問問自己,如果您返回一個虛擬的布爾值(存儲在類中),那么調用者會知道索引是否無效嗎? 沒有。
//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];
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.