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;
}
According to code you showed, your
nameis global variable. It means, it is only onenamevariable in your program for all instances offooClass. And every time you executeyou change the value of that variable.
If you want each
fooClassto have its own name, you should make yournamevariable member offooClasslike that: