Using the operator<< with a QStringList pointer

风流意气都作罢 提交于 2019-12-11 03:37:51

问题


How I can change this code?

QString s="123";
QStringList *myList=new QStringList;

myList<<s;

Error:

no match for 'operator<<' (operand types are 'QStringList*' and 'QString')

*myList<<s;

does not work too: myList is Empty, after this.


回答1:


There is little to no point in using a pointer for a QStringList because this is an implicitly shared class due to the copy-on-write. You can find further details for that below:

http://qt-project.org/doc/qt-5.1/qtcore/implicit-sharing.html

Which means, I would refactor your code to look like this:

QString s="123";
QStringList myList;

myList << s;

Note, you also had a typo for myList as you seem to have written myLis. That is at least one syntax error which would lead to compilation error. You could also use the C++11 syntax for this if you have support for that:

QString s="123";
QStringList myList({s});

This will come to handy when you will have more elements to insert without continuous append lines separately.

However, if you are still interested in doing this for some reason, you should consider this:

myList->append(s);

or as a last resort even your line should work if you had not done any other mistakes. This should be the whole code to see if you had done any other mistakes:

main.cpp

#include <QStringList>
#include <QDebug>

int main()
{
    QString s="123";
    QStringList *myList = new QStringList;
    *myList<<s;
    qDebug() << *myList;
    return 0;
}

Building (something similar)

g++ -Wall -fPIC -I/usr/include/qt -I/usr/include/qt/QtCore -lQt5Core main.cpp && ./a.out

Output

("123")



回答2:


<< is a much overloaded operator. I think you should try

(*myList)<<s;

edit I just tested, and *myList << s; seems to work... Maybe you have some other problem...




回答3:


If you are using pointer to QStringList you must delete it manually after using, 'cause this class isn't QOBJECT and doesn't use Qt garbage collector system.



来源:https://stackoverflow.com/questions/19178815/using-the-operator-with-a-qstringlist-pointer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!