我一直在搞乱Qt和C ++,但是我遇到了这个错误,似乎无法弄清楚它为何会突然出现。使用const void *转换错误消息已经解答了很多其他问题,但是我无法真正看到解释在我的情况下如何帮助,所以这里有:
我有一个QList的重新实现'MyTypeManager'< MyType * const>,所以是指向非const MyTypes的const指针列表。但是,当我重新实现一个函数时,addMyType被称为
void MyTypeManager::addMyType(MyType *const var)
{
this->append(var);
}
发生以下错误:
In file included from /usr/include/qt4/QtCore/QList:1:0,
from ../qtsdlthread/mytypemanager.h:4,
from ../qtsdlthread/mytypemanager.cpp:1:
/usr/include/qt4/QtCore/qlist.h: In member function ‘void QList<T>::node_construct(QList<T>::Node*, const T&) [with T = MyType* const]’:
/usr/include/qt4/QtCore/qlist.h:499:13: instantiated from ‘void QList<T>::append(const T&) [with T = MyType* const]’
../qtsdlthread/mytypemanager.cpp:20:26: instantiated from here
/usr/include/qt4/QtCore/qlist.h:359:58: error: invalid conversion from ‘const void*’ to ‘void*’
/usr/include/qt4/QtCore/qlist.h: In member function ‘void QList<T>::node_copy(QList<T>::Node*, QList<T>::Node*, QList<T>::Node*) [with T = MyType* const]’:
/usr/include/qt4/QtCore/qlist.h:666:9: instantiated from ‘QList<T>::Node* QList<T>::detach_helper_grow(int, int) [with T = MyType* const]’
/usr/include/qt4/QtCore/qlist.h:497:48: instantiated from ‘void QList<T>::append(const T&) [with T = MyType* const]’
../qtsdlthread/mytypemanager.cpp:20:26: instantiated from here
/usr/include/qt4/QtCore/qlist.h:386:17: error: invalid conversion from ‘const void*’ to ‘void*’
mytypemanager中的20:26是上面发布的this-&gt;追加行。
答案 0 :(得分:4)
QList的值类型必须是可分配的数据类型。
Alas MyType *const
不可转让。你有几种补救措施:
T
成为可变指针T
成为指向const指针的指针:typedef MyType *const Element
void MyTypeManager::addMyType(Element var)
{
Element* ptr2ptr = new Element(var);
this->append(ptr2ptr);
}
但是现在你需要担心2级内存管理。
T=MyType*
和常规MyType *const
设为MyType *
:this->append(const_cast<MyType *>(var));
这只有在您确定var
最初是作为MyType*
变量创建时才有效。