W
wutongjoe
Hi,I had a problem while I was doing the assignment .the code is like
below(not exact):
//======================================
class Buyer
{
private:
int _product;
public:
//Buyer(void){ _product=-1;
int get_product(void);
Buyer( int n ){ _product = n;};
};
int Buyer::get_product(void){
return _product;
};
std::vector<Buyer *> buyer_queue;
int main( int argc, char *argv[] )
{
for(;{
int i=int(1+rand()%10);
Buyer b=Buyer(i);
buyer_queue.push_back(&b);
printf("\nB[%d]",(*buyer_queue[buyer_queue.size()-1]).get_product());
for (int j=0;j<buyer_queue.size();j++){
printf("\t\n looped [%d]",(*buyer_queue[j]).get_product());
}
usleep(1000000);
}
}
//====================================
the problem is in the for loop,why it outputs the same value for
member"product" of each Buyer?
below(not exact):
//======================================
class Buyer
{
private:
int _product;
public:
//Buyer(void){ _product=-1;
int get_product(void);
Buyer( int n ){ _product = n;};
};
int Buyer::get_product(void){
return _product;
};
std::vector<Buyer *> buyer_queue;
int main( int argc, char *argv[] )
{
for(;{
int i=int(1+rand()%10);
Buyer b=Buyer(i);
buyer_queue.push_back(&b);
printf("\nB[%d]",(*buyer_queue[buyer_queue.size()-1]).get_product());
for (int j=0;j<buyer_queue.size();j++){
printf("\t\n looped [%d]",(*buyer_queue[j]).get_product());
}
usleep(1000000);
}
}
//====================================
the problem is in the for loop,why it outputs the same value for
member"product" of each Buyer?