Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Appending and Iterating Through QList

Tags:

c++

qt

My QList holds pointers to a class. I am trying to iterate through the QList, but all its elements seems to only contain the last pointer I assigned to the QList.

code:

QList<fooClass*> myList;

fooClass *pNewFooA = new fooClass("Bob");
myList.append(pNewFooA);

fooClass *pNewFooB = new fooClass("Jen");
myList.append(pNewFooB);

fooClass *pNewFooC = new fooClass("Mel");
myList.append(pNewFooC);

QList<fooClass*>::iterator i;
for (i = myList.begin(); i != myList.end(); i++) {
    cout << (*i)->getName() << "\n";
}

output:

Mel
Mel
Mel

Instead of using .append(), I also have tried the following but it did not work:

  • myList.push_back("zoe");
  • myList << "zoe";
  • myList += "zoe";

fooClass.cpp

QString name = "";

QString fooClass::getName()
{
    return name;
}

fooClass::fooClass(QString newName)
{
    name = newName;
}
like image 340
Jon Avatar asked Feb 17 '12 20:02

Jon


2 Answers

According to code you showed, your name is global variable. It means, it is only one name variable in your program for all instances of fooClass. And every time you execute

name = newName;

you change the value of that variable.

If you want each fooClass to have its own name, you should make your name variable member of fooClass like that:

class fooClass
{
public:
    //some stuff here
private:
    QString name;
};
like image 159
Lol4t0 Avatar answered Sep 21 '22 06:09

Lol4t0


The problem is not in your list, make name private member of your fooClass in the header. Should be like that

class fooClass{
public:
  fooClass(QString newName);
  QString getName();
private:
  QString name;
};

And remove global variable name from cpp. You don't need to init QString with "" anyway.

like image 37
Dmitriy Kachko Avatar answered Sep 23 '22 06:09

Dmitriy Kachko