【问题标题】:reference to type 'Item *const' could not bind to an rvalue of type 'const Item *'对“Item *const”类型的引用无法绑定到“const Item *”类型的右值
【发布时间】:2018-08-22 15:28:20
【问题描述】:

我尝试从没有const 项目的列表中抑制 const 项目指针:

#include <QString>
#include <QList>

class Item {
public:
    Item(QString name) : _name(name) {
    }
private:
    QString _name;
};

class Product {
public:
    Product(const Item * item) : _item(item) {
    }

    const Item * item() {
        return _item;
    }

    void setItem(const Item * item) {
        _item = item;
    }
private:
    const Item * _item;
};

int main() {
    QList<Item*> listOfNonConstItem;
    listOfNonConstItem.append(new Item("a"));
    listOfNonConstItem.append(new Item("b"));

    Product product(listOfNonConstItem.first());
    listOfNonConstItem.removeOne(product.item());

    return 0;
}

很遗憾,编译失败:

/path/to/main.cpp:34:31: error: reference to type 'Item *const' could not bind to an lvalue of type 'const Item *'
    editableList.removeOne(pC);
                           ^~
/path/to/Qt/5.6.3/clang_64/lib/QtCore.framework/Headers/qlist.h:201:29: note: passing argument to parameter 't' here
bool removeOne(const T &t);
                        ^

我不明白为什么会出现问题,因为removeOne()参数是const

【问题讨论】:

  • 不要将指针与指针混淆。
  • pointee 是什么意思?
  • 指向的对象类型。在指针类型中表示为星号 * 之前的任何内容。
  • @LogicStuff 我刚刚编辑了我的示例,所以行号匹配
  • 顺便说一句,在有人帮助您解决原始问题之后,在您的帖子中添加一个完全独立的问题(您甚至承认原始问题已通过下面的答案解决),这是不好的 Stack Overflow 礼仪.我建议您恢复编辑,接受答案,然后发布一个新问题。

标签: c++ list qt pointers constants


【解决方案1】:

您对const 指针和指向const 的指针感到困惑。

removeOne 期望的是指针(即Item*);对于参数声明,const 在指针上是合格的,但在指针上不合格(即Item* const &amp;,引用 const 指针到非 const Item)。虽然您传递的是指向const(即const Item*)的指针,但它不能隐式转换为指向非常量的指针。

pC 的类型更改为Item*Item* const 即可解决问题。

【讨论】:

  • 这修复了我的示例,但实际上我想要做的有点复杂。我更新了我的代码以更好地解释我想要做什么。
  • 自从你解决了我的第一个问题后,我将恢复我的编辑!
猜你喜欢
  • 2020-05-08
  • 2020-09-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-21
  • 1970-01-01
  • 2022-01-08
相关资源
最近更新 更多