从'MyClass <int> :: iterator*'类型的临时类中初始化'int&'类型的非const引用

exs*_*ape 2 c++ iterator reference

在尝试为我的链表类添加迭代器支持时,我从g ++中收到以下错误.

LinkedList.hpp: In member function ‘Type& exscape::LinkedList<Type>::iterator::operator*() [with Type = int]’:  
tests.cpp:51:   instantiated from here  
LinkedList.hpp:412: error: invalid initialization of non-const reference of type ‘int&’ from a temporary of type ‘exscape::LinkedList<int>::iterator*’

可能相关的代码片段:

LinkedList.hpp:

template <typename Type>
class LinkedList {
    private:
        struct node {
            struct node *prev;
            struct node *next;
            Type data;
        };
    public:
        class iterator : public std::iterator<...> {
            node *p;

        public:
             Type &operator*();
        };
...
};

template <typename Type>
LinkedList<Type>::iterator::iterator(struct node *in_node) : p(in_node) {}

template <typename Type>
inline Type &LinkedList<Type>::iterator::operator*() {
    return this-p->data; ///// Line 412
}
Run Code Online (Sandbox Code Playgroud)

tests.cpp:

...
LinkedList<int> l1;
...
LinkedList<int>::iterator it;
for (it = l1.begin(); it != l1.end(); ++it) {
    std::cout << "Element: " << *it << std::endl; ///// Line 51
}
Run Code Online (Sandbox Code Playgroud)

我用谷歌搜索(当然也搜索了),并检查我的代码无济于事 - 要么我缺少一些基本的东西(也就是做一些愚蠢的事情),或者我缺少所需的知识.有什么建议?

Kea*_*eks 5

你正在返回一个临时对象的引用:( this - p->data我强调错字)计算指针间隔,操作的结果是临时右值:你不能从中获取引用.

只需删除拼写错误:

this->p->data;
Run Code Online (Sandbox Code Playgroud)