c++ - 为什么我在以下代码中收到 "must be modifiable l-value"编译器错误 (C2105)?

标签 c++ compiler-errors iterator

我被这个难住了......编译器输出:

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/

相关文章:

对具有无界通配符类型的方法参数使用泛型 lambda 的 Java 编译错误

java - 错误,我无法删除临时文件或将其替换为原始文件java

PHP RecursiveArrayIterator类递归获取键值对

c++ - 指向 const 成员函数 typedef 的指针

C++ 从 void* 中恢复指向未知关联容器的元素

c++ - 通过迭代器更改集合中的元素

iterator - Java 8 迭代器流到迭代器会导致对 hasNext() 的冗余调用

python-2.7 - PYTHON 2.7 - 修改列表列表并重新组装而不改变

c++ - 如何在 C++ 中使用两个排序标准(对于一组对)创建一个有序集?

c++ - 我可以访问临时对象的成员吗?