Segfault iterating over a QList
I've created two classes - one called circle:
class circle
{
public:
circle();
QString name ;
int id ;
};
and another class that use this class:
class soso
{
public:
soso();
QList<circle*> lis;
void go();
};
In the constructor of soso I add two circles:
soso::soso()
{
circle* c1 = new circle();
circle* c2= new circle();
c1->id=1;
c1->name="yamen开发者_开发知识库";
c2->id=2;
c2->name="hasan";
lis.append(c1);
lis.append(c2);
}
and in the main window i've called go method which is included here
void soso::go()
{
QFile file("database.txt");
if(!file.open(QIODevice::WriteOnly))
throw " cannot open file ! ";
QDataStream out(&file);
int i=0;
QList<circle*>::iterator it1 =lis.begin();
for(i=0;it1!=lis.end();it1++);
{
out<<(*it1)->id; // segmentation error here
out<<(*it1)->name;
}
}
But I am getting a segmentation error. What am I doing wrong?
You have a semicolon after your for loop! Those are really hard to notice.
for(i=0;it1!=lis.end();it1++);
This works. Just changed it to look more like standard use of iterators:
QList<circle*>::iterator it1;
for(it1 = lis.begin();it1!=lis.end();it1++)
{
out<<(*it1)->id;
out<<(*it1)->name;
}
精彩评论