使用Qt:使用QList <type * const =“”> </type>时,从const void *到void *的转换无效

时间:2011-09-02 15:03:17

标签: c++ qt pointers const qlist

我一直在搞乱Qt和C ++,但是我遇到了这个错误,似乎无法弄清楚它为何会突然出现。使用const void *转换错误消息已经解答了很多其他问题,但是我无法真正看到解释在我的情况下如何帮助,所以这里有:

我有一个QList的重新实现'MyTypeManager'&lt; MyType * const&gt;,所以是指向非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;追加行。

1 个答案:

答案 0 :(得分:4)

来自documentation

  

QList的值类型必须是可分配的数据类型。

Alas MyType *const不可转让。你有几种补救措施:

1。使T成为可变指针

2。使T成为指向const指针的指针:

typedef MyType *const Element

void MyTypeManager::addMyType(Element var)
{
    Element* ptr2ptr = new Element(var);
    this->append(ptr2ptr);
}

但是现在你需要担心2级内存管理。

3。 (危险)将T=MyType*和常规MyType *const设为MyType *

this->append(const_cast<MyType *>(var));

这只有在您确定var最初是作为MyType*变量创建时才有效。