2014-04-03 60 views
5

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

#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在siganture结束,它编译...

谢谢!

+0

你传递它需要一个参考指针。 – OMGtechy

+0

@OMGtechy,对指针的引用。 – chris

+0

'const T&'当'T'是'Node *'时表示'Node * const&',而不是'const Node *&'。 – chris

回答

4

问题是在这里:

n->_adjacent.contains(this) 

由于包含假定它会得到Node* constthisconst Node*类型。添加const不是问题,但删除是一个问题。因此,尝试const_cast这样的:

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

谢谢,这工作。我认为'this'的类型是'const Node * const',这是我最初的错误。 – ddeunagomez

1

在你的“isConnectedTo”函数中,“this pointer”是一个const Node * const指针,意思是“this”不能用来改变它引用的Node对象的内容。在您的调用“n - > _ adjacent.contains(this)”中,您将“this”指针传递给具有常量参考参数(const T & ref,其中T是Node *)的函数。 const T & ref其中T是节点*意味着ref是节点* const &,即对指针的常量引用。这里的常量指的是指针,意味着引用不能用来改变指针。但是,这并不意味着引用不能用于更改指针指向的对象(节点)。所以没有什么能阻止我们做类似(* ref).call_to_non_const_function_in_Node的事情。

但你的情况下的“this”指针指向一个常量Node对象。这就是为什么这个代码不能编译。如果参数是一个常量Node * const &,即对常量指针的常量引用,它会编译。当您从成员函数中删除const修饰符时,“this”只是一个常规的Node * const指针,这就是为什么它编译。

0

如果您不打算通过_adjacent列表更改Node S,改变其声明

QList<const Node*> _adjacent; 

否则你可能不得不求助于const_cast,或者从你的函数删除const预选赛。

相关问题