【问题标题】:Error: binding to reference of type discards qualifiers错误:绑定到类型丢弃限定符的引用
【发布时间】:2018-08-26 13:29:11
【问题描述】:

很抱歉,我知道以前有人问过这个问题,但即使我尝试阅读类似问题的所有其他答案,我也无法理解我的错误。 我正在使用 Eclipse,我正在使用 C++ 进行编程,并且我正在尝试使用模板制作一个 链接列表

我正在使用一个对我的链表有用的节点类,并且我有这个函数规范:

template <class item>
void list_insert(node<item>*& head, const item&e);

好的。我想在我的 list 类中使用这个功能,我可以有这个:

template <class item>
class list{
public:
    list(){head=NULL;}

    void set_head(node<item>*h){head=h;}
    node<item>*& get_head(){return head;}
    const node<item>* get_head()const{return head;}

    bool empty()const{return head==NULL;} // is the list empty?

    void insert(const item&e){list_insert(head,e);} //ERROR GETS HERE!
    void print(); // print the list clockwise
    void printback(); //print it counterclockwise

private:
    node<item>* head;
};

我这样做是为了像这样实现 list_insert:

template <class item>
void list_insert(node<item>*& head, const item& e){
    head= new node<item>(e,head);
}

现在,在最后一段代码中,我得到了这个错误:

错误:将“const int”绑定到“int&”类型的引用会丢弃限定符

我读过基本上编译器告诉我''ehi,如果你这样做,你想要的 const 条件将被违反,所以我给你一个错误'',好吧,但我还是不明白实际错误,或者无论如何,它背后的原因是什么。

也因为我也应该做一个逆时针插入功能,但实际上我在顺时针时遇到了麻烦,所以我很卡住。

非常感谢您。

编辑:很抱歉,我没有提供我正在做的实际示例。 基本上,我正在尝试制作一个链接列表 - 对我的考试来说简单而基本。

我的链表基本上是由节点组成的堆栈。节点是我列表的组成部分,由数据部分和到下一个节点部分的链接组成:

template <class item>
class node{
public:
    //CONSTRUCTOR
    nodo(item & d=item(), nodo*l=NULL){
        data=d;
        link=l;
    }

    //GET E SET METHODS
    void set_data(item& d){data=d;}
    void set_link(node*l){link=l;}

    item& get_data(){return data;}
    const item& get_data()const{return data;}
    node*& get_link(){return link;}
    const node* get_link()const{return link;}

private:
    item data;
    node* link;
};

现在,如上所述,我的列表由节点组成,在私有部分中,我声明了一个指向列表头部的指针。

 node<item>* head;

这就是这段代码的例子——然后问题就出现了,就像我之前写的那样。

【问题讨论】:

  • 错误信息已经够清楚了。有什么问题?
  • 查看节点构造函数的声明。
  • 问题是我在 main 中使用了 作为 ,但是对于我使用的每种数据类型,该函数一直存在与 const 声明的绑定问题。正如编译器所说,这是一个绑定问题,但我无法理解它,因为我实际上是在推理变量。并且错误一直出现在我的 list_insert 函数的实现中。
  • 请提供 MCVE。什么是“节点”? -- minimal reproducible example
  • 啊,对不起,我的错。我把帖子编辑了。好点了吗?

标签: c++ eclipse binding linked-list


【解决方案1】:

node 的构造函数中,您应该通过 const-reference 传递 item(并且有一些错字,可能是您的 node 类中的复制+粘贴错误。

class node{
public:
    //CONSTRUCTOR
    node(item const & d=item(), node*l=0)
        : data(d), link(l) // prefer initializer list here
    { }
    //...

【讨论】:

  • ohmygoditworked。是的,对不起,错字是因为复制+粘贴错误,我很抱歉,但它确实有效。构造函数我其实没有想过,说实话,我是痴迷于我的函数的实现。这就是为什么我实际上意识到构造函数有一些问题为时已晚,我很抱歉。无论如何,非常感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-01-07
  • 2015-11-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-07
相关资源
最近更新 更多