C++ 初始化类型为‘;的非常量引用无效;国际及';从类型为';MyClass<;int>;::迭代器*';

C++ 初始化类型为‘;的非常量引用无效;国际及';从类型为';MyClass<;int>;::迭代器*';,c++,reference,iterator,C++,Reference,Iterator,在尝试为我的链表类添加迭代器支持时,我从g++中得到以下错误 LinkedList.hpp:在成员函数“Type&exscape::LinkedList::iterator::operator*()[with Type=int]”中: tests.cpp:51:从此处实例化 LinkedList.hpp:412:错误:从类型为“exscape::LinkedList::iterator*”的临时文件初始化类型为“int&”的非常量引用无效 可能的相关代码片段: LinkedList.hpp: t

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

LinkedList.hpp:在成员函数“Type&exscape::LinkedList::iterator::operator*()[with Type=int]”中: tests.cpp:51:从此处实例化 LinkedList.hpp:412:错误:从类型为“exscape::LinkedList::iterator*”的临时文件初始化类型为“int&”的非常量引用无效 可能的相关代码片段:

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
}
模板
类链接列表{
私人:
结构节点{
结构节点*prev;
结构节点*下一步;
类型数据;
};
公众:
类迭代器:public std::iterator{
节点*p;
公众:
类型和运算符*();
};
...
};
模板
LinkedList::iterator::iterator(结构节点*在节点中):p(在节点中){
模板
内联类型&LinkedList::迭代器::运算符*(){
返回此-p->data;//第412行
}
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
}
。。。
链接列表l1;
...
LinkedList::迭代器;
for(it=l1.begin();it!=l1.end();+it){

std::cout这个问题可以通过以下代码片段来演示

struct A {
  int a;
  A *get() { return this - a; }
};

int main() { A a = { 0 }; assert(&a == a.get()); }
将行412替换为以下内容

return this->p->data; // "this->" is optional

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

只需删除输入错误:

this->p->data;

看起来你可能在第412Ugh行有一个拼写错误!就是这样,谢谢。我猜拼写错误属于前一类错误…;)事实上,这个->并不总是可选的。当处理从其他模板类继承的模板类时,可能需要它:@Marius,是的,但在这里它是可选的。我不敢尝试将我所有的语句都括起来用C++中发现的所有例外,这对人们来说并没有帮助,它也偷走了我的时间:
this->p->data;