为什么使用迭代器和范围的斐波那契数列会抛出错误 我在CPP崩溃课程书中练习C++代码片段(第8章,练习1),下面没有编译,程序的错误已经在下面提供了。如果提供任何建议或链接以供理解,将非常有帮助。:)

为什么使用迭代器和范围的斐波那契数列会抛出错误 我在CPP崩溃课程书中练习C++代码片段(第8章,练习1),下面没有编译,程序的错误已经在下面提供了。如果提供任何建议或链接以供理解,将非常有帮助。:),c++,c++11,logic,c++17,C++,C++11,Logic,C++17,您的begin和end成员函数返回不同的类型。在C++17之前,这些类型需要相同,如错误消息所示 错误:基于范围的“for”语句中的开始/结束类型不一致 从C++17开始,对循环的限制放宽了 从C++17开始,begin_expr和end_expr的类型不必相同,事实上end_expr的类型不必是迭代器:它只需要能够与迭代器进行不等式比较。这使得通过谓词(例如“迭代器指向空字符”)来限定范围成为可能 因此,如果您使用C++17编译代码,通过传递-std=C++17标志,您的代码将被编译,前提是它

您的
begin
end
成员函数返回不同的类型。在C++17之前,这些类型需要相同,如错误消息所示

错误:基于范围的“for”语句中的开始/结束类型不一致

从C++17开始,对循环的限制放宽了

从C++17开始,
begin_expr
end_expr
的类型不必相同,事实上
end_expr
的类型不必是迭代器:它只需要能够与迭代器进行不等式比较。这使得通过谓词(例如“迭代器指向空字符”)来限定范围成为可能


因此,如果您使用C++17编译代码,通过传递
-std=C++17
标志,您的代码将被编译,前提是它满足所有其他约束,确实如此。

循环范围内的开始和结束迭代器的不同类型是C++17特性。用
-std=c++17
编译代码。@cigien感谢它的工作。
#include <cstdio>
struct FibonacciIterator {
    bool operator!=(int x) const {
    return x >= current; 
    }
    FibonacciIterator& operator++() {
    const auto tmp = current; 
    current += last; 
    last = tmp; 
    return *this;
    }
    int operator*() const {
    return current;
    }
private:
    int current{ 1 }, last{ 1 };
};

struct FibonacciRange {
    explicit FibonacciRange(int max) : max{ max } { }
    FibonacciIterator begin() const { 
    return FibonacciIterator{};
    }
    int end() const { 
    return max;
    }
private:
    const int max;
};

int main() {
    for (const auto i : FibonacciRange{ 50 }) {
    printf("%d ", i); 
    }
}

user@stretch:/tmp$ g++ test.cpp -o test
test.cpp: In function ‘int main()’:
test.cpp:32:46: error: inconsistent begin/end types in range-based ‘for’ statement: ‘FibonacciIterator’ and ‘int’
     for (const auto i : FibonacciRange{ 5000 }) {
                                              ^
test.cpp:32:46: error: conversion from ‘int’ to non-scalar type ‘FibonacciIterator’ requested
test.cpp:32:46: error: no match for ‘operator!=’ (operand types are ‘FibonacciIterator’ and ‘FibonacciIterator’)
test.cpp:3:10: note: candidate: bool FibonacciIterator::operator!=(int) const
     bool operator!=(int x) const {
          ^~~~~~~~
test.cpp:3:10: note:   no known conversion for argument 1 from ‘FibonacciIterator’ to ‘int’