Adding and iterating through a QList

My QList contains pointers to a class. I am trying to iterate through a QList, but all of its elements seem to contain only the last pointer assigned by QList.

the 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"; } 

exit:

 Mel Mel Mel 

Instead of using .append (), I also tried the following, but this 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; } 
+4
source share
2 answers

According to the code you provided, your name is a global variable. This means that in your program there is only one variable name for all instances of fooClass . And every time you do

 name = newName; 

you are changing the value of this variable.

If you want each fooClass have its own name, you must make your name member variable fooClass as follows:

 class fooClass { public: //some stuff here private: QString name; }; 
+4
source

The problem is not on your list, enter the name of the 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 the global variable name from cpp. In any case, you do not need to initialize the QString with "".

+1
source

Source: https://habr.com/ru/post/1397103/


All Articles