Question

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.

Was it helpful?

Solution

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")

OTHER TIPS

<< 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...

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top