【问题标题】:'begin' was not declared in this scope'begin' 未在此范围内声明
【发布时间】:2016-08-09 11:19:33
【问题描述】:

我有这样的课程(我只留下相关部分):

    template<class T>
    class MyList
    {
    public:
    // ....

    typename QList<T*>::iterator begin()
    {
        return list.begin();
    }

    typename QList<T*>::iterator end()
    {
        return list.end();
    }

    typename QList<T*>::iterator skip(int n)
        {
            auto ite = list.begin();

            while(n --> 0)
                ++ite;

            return ite;
        }

       QList<T*> list;
    };

我去上课的时候:

MyList<Foo*> foo;
for(Foo* f : foo.skip(1)) {

我收到此错误:

'begin' 没有在这个范围内声明

我删除了skip() 调用,循环工作正常...我不明白为什么。为什么会这样,我该如何解决?

【问题讨论】:

    标签: qt c++11 iterator


    【解决方案1】:

    这正是基于范围的 for 循环在 C++ 中的工作方式。特别是,当在范围表达式中参与者是类类型时,在您的情况下为 MyList,要使表达式合法,类类型必须具有定义的成员 beginend

    成员函数MyList::skip 将迭代器返回到QList&lt;T*&gt;。此迭代器类未定义任何 beginend 成员,编译器将此类型(即迭代器)呈现为不是基于范围的 for 循环表达式的合法参与者,而已定义的类类型 MyList成员 beginend 呈现合法。

    有关 range-for 循环如何工作的更多信息,您可以找到 here

    【讨论】:

    • 我混淆了 C++ 和 Qt 的迭代器
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-20
    • 2019-02-17
    • 2021-01-07
    • 2016-10-27
    • 2016-06-03
    • 2014-09-11
    相关资源
    最近更新 更多