C++ 从 ‘const type* const’ 到 ‘type*’ 的无效转换

标签 c++ qt

我有一个非常愚蠢的问题(我认为)。很长时间没有用 C++ 编码,但我无法弄清楚这个问题。 我有这个类:

#include <QList>
class Node {
private:
    QList<Node*> _adjacent;
public:
    Node();
    bool isConnectedTo(Node* n) const;
};

isConnectedTo() 的实现:

bool Node::isConnectedTo(Node* n) const{
    return _adjacent.contains(n) && n->_adjacent.contains(this);
}

我在 return 行中收到以下错误:

Node.cpp: In member function ‘const bool Node::isConnectedTo(Node*) const’:
Node.cpp:25:60: error: invalid conversion from ‘const Node* const’ to ‘Node*’ [-fpermissive]
In file included from /usr/include/qt5/QtCore/QList:1:0,
                 from Node.hpp:5,
                 from Node.cpp:1:
/usr/include/qt5/QtCore/qlist.h:913:27: error:   initializing argument 1 of ‘bool QList<T>::contains(const T&) const [with T = Node*]’ [-fpermissive]

我认为,既然方法是常量,那么这里的this就是const Node* const类型。 通过阅读 Qt 文档,我看到 QList::contains 的类型为 bool QList::contains(const T & value) const 所以它应该没问题,对吧?我的意思是,它需要一个 const Node*,而一个 const Node* const 是它的一个特例,所以... 通过删除符号末尾的 const,它编译...

谢谢!

最佳答案

问题在这里:

n->_adjacent.contains(this)

因为 contains 假定它将获得 Node* const 并且 thisconst Node* 的类型。添加 const 不是问题,但删除是个问题。所以像这样尝试 const_cast:

n->_adjacent.contains(const_cast<Node* const>(this))

关于C++ 从 ‘const type* const’ 到 ‘type*’ 的无效转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22837374/

相关文章:

c++ - "Rule of Three"的实现出错

c++ - 警告控制到达非空函数 c++ 的末尾

c++ - 标准在哪里定义了将值绑定(bind)到引用的优先顺序?

c++ - 来自 std::string 的高效 QVariant 构造

c++ - 在没有管理员权限的情况下获取主域 SID

c++ - 本地类访问问题

qt - FUSE(用户空间中的文件系统)与 Qt 编程

c++ - QT的UDP广播

c++ - 多维数组的Qt QVector

c++ - 使用 qmake 查找编译器供应商/版本