简体   繁体   English

const_iterator超过引用的指针列表

[英]const_iterator over referenced list of pointers

There is a thing I really can't understand. 我真的不明白。 Following Situation: 以下情况:

Test.h file: Test.h文件:

class Test{
    public:
        const std::list<Item*>& getItems() { return m_items; }
        void showSomething() const;
    private:
        std::list<Item*> m_items;
}

Test.cpp file: Test.cpp文件:

void Test::showSomething() const{
    for (std::list<Item*>::const_iterator item_it = getItems().begin(); item_it != getPlayers().end(); item_it++) {
        doSomething();
    }
}

Visual Studio tells me, that this doesn't work and underlines getItems() in the for loop. Visual Studio告诉我,这不起作用,并在for循环中强调了getItems()。 The error translates something like "type qualifier is not compatible with member function getItems ... the Object is const Test". 该错误翻译为“类型限定符与成员函数getItems不兼容...对象为const测试”。

I know that getItems() returns a const reference to the list of Item-Pointers. 我知道getItems()返回对项指针列表的const引用。 But why can't I use it in the for loop? 但是,为什么不能在for循环中使用它呢?

You missed const . 您错过了const

Try this: 尝试这个:

const std::list<Item*>& getItems() const { return m_items; }

You need const, because showSomething method, from which getItems is called is const. 您需要const,因为showSomething调用getItems showSomething方法是const。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM