我有一个非常愚蠢的问题(我认为)。很长时间没有用 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
并且 this
是 const Node*
的类型。添加 const
不是问题,但删除是个问题。所以像这样尝试 const_cast
:
n->_adjacent.contains(const_cast<Node* const>(this))
关于C++ 从 ‘const type* const’ 到 ‘type*’ 的无效转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22837374/