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:
fooClass.cpp
QString name = "";
QString fooClass::getName()
{
return name;
}
fooClass::fooClass(QString newName)
{
name = newName;
}
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;
};
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With