我已经扩展了C++ 11 std::array
,它是工作文件,但是当我试图重载operator[]
时,我得到了以下错误:
error: lvalue required as left operand of assignment
array[0] = 911;
^~~
是否可以为operator[]
类型实现std::array
添加绑定检查?
这是代码:
#include <array>
#include <cassert>
#include <iostream>
template <unsigned int array_size, typename array_datatype=long int>
struct Array : public std::array<array_datatype, array_size>
{
Array()
{
}
// std::array constructor inheritance
// https://stackoverflow.com/questions/24280521/stdarray-constructor-inheritance
Array(std::initializer_list< array_datatype > new_values)
{
unsigned int data_size = new_values.size();
unsigned int column_index = 0;
// std::cout << data_size << std::endl;
if( data_size == 1 )
{
this->clear(*(new_values.begin()));
}
else
{
assert(data_size == array_size);
for( auto column : new_values )
{
(*this)[column_index] = column;
column_index++;
}
}
}
array_datatype operator[](unsigned int line)
{
assert(line < array_size);
assert(line > -1);
return (*this)[line];
}
/**
* Prints a more beauty version of the array when called on `std::cout<< array << std::end;`
*/
friend std::ostream& operator<<( std::ostream &output, const Array &array )
{
unsigned int column;
output << "{";
for( column=0; column < array_size; column++ )
{
output << array[column];
if( column != array_size-1 )
{
output << ", ";
}
}
output << "}";
return output;
}
}
相关信息:
发布于 2018-03-22 02:08:22
如果要在赋值的左侧使用operator[]
的返回值,则必须通过引用而不是按值返回数组元素。
您还具有一个递归循环,因为您正在从自身内部调用自己的operator[]
。您希望调用基类的operator[]
,因此需要对其进行限定。
试试这个:
array_datatype& operator[](unsigned int line)
{
assert(line < array_size);
assert(line > -1);
return std::array<array_datatype, array_size>::operator[](line);
}
发布于 2018-03-22 01:30:33
您可以使用:
array_datatype& operator[](unsigned int line)&
array_datatype const& operator[](unsigned int line)const&
array_datatype operator[](unsigned int line)&&
发布于 2018-03-24 19:10:30
如果希望绑定检查对数组元素的访问,只需使用std::vector
(或std::array
)的std::vector
方法(或std::array
),而不是[]
运算符。为了这个目的,不要重新发明轮子:)。
有关数组边界检查的文档,请参见参考文献。
https://stackoverflow.com/questions/49419089
复制相似问题