我被这个难住了......编译器输出:
d:\data\personal\projects\test\test.cpp(42): 错误 C2105: '--' 需要左值
#include <iostream>
#include <algorithm>
#include <iterator>
class FOO
{
public:
typedef int* iterator;
typedef const int* const_iterator;
class explicit_iterator : public std::iterator< std::bidirectional_iterator_tag, int >
{
public:
explicit_iterator(int* ptr = nullptr) : m_ptr(ptr) {}
bool operator ==(const explicit_iterator& rhs) const { return m_ptr == rhs.m_ptr; }
bool operator !=(const explicit_iterator& rhs) const { return m_ptr != rhs.m_ptr; }
reference operator *() const { return *m_ptr; }
explicit_iterator& operator ++() { ++m_ptr; return *this; }
explicit_iterator& operator --() { --m_ptr; return *this; }
private:
int* m_ptr;
};
FOO(int val = 0) { std::fill( begin(), end(), val ); }
iterator begin() { return m_data; }
iterator end() { return m_data + 10; }
explicit_iterator begin2() { return explicit_iterator( begin() ); }
explicit_iterator end2() { return explicit_iterator( end() ); }
private:
int m_data[10];
};
int main (int, char *[])
{
FOO foo;
// This is the line that fails! (Not this one, the one right below!!!)
std::copy( foo.begin(), --foo.end(), std::ostream_iterator<int>( std::cout, "\n" ) ); // C2105
// All these variants are good
std::copy( foo.begin2(), --foo.end2(), std::ostream_iterator<int>( std::cout, "\n" ) ); // good
std::copy( foo.begin(), foo.end() - 1, std::ostream_iterator<int>( std::cout, "\n" ) ); // good
int* end = foo.end();
std::copy( foo.begin(), --end, std::ostream_iterator<int>( std::cout, "\n" ) ); // good
return 0;
}
最佳答案
您不能预减右值或指针类型。调用 foo.end()
返回一个右值 int*
并且您不能预先递增/预先递减它。
下一个调用起作用--foo.end2()
,因为在这种情况下预增量是一个成员函数,并且在该语言中对右值调用成员函数是合法的。语法相当于更明确的语法,这可能会使它更容易理解:
foo.end2().operator--();
关于c++ - 为什么我在以下代码中收到 "must be modifiable l-value"编译器错误 (C2105)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19715501/