gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 01:07:10 26 4
gpt4 key购买 nike

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

d:\data\personal\projects\test\test.cpp(42): error 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com