yTpo yTpo - 1 year ago 69
C++ Question

How to correctly set up a istream& operator>> for an array item?

So I have a dynamically made queue, and I'm trying to overload the >> operator for it. But the number I enter is wrong. Any guesses on what I'm doing wrong? (the << operator works just fine though).
So my class is:

class queue
int queue1[100];
int rear1,front1, num1;
queue(): rear1(-1),front1(-1){};
queue(int , int , int);

void insert1(int );
void delet1();

friend istream& operator>>(istream& in, queue& obj);

friend ostream& operator<<(ostream& out, const queue& obj);
void queue::printOn(ostream &out) const;


and the function operator itself:

istream& operator>>(istream& in, queue& obj){
in >> obj.queue1[obj.rear1++];
cout <<"inserted: " << obj.queue1[obj.rear1];

and my main funtion is:

queue qu1;
cout<<"Entered number:";
cout << qu1;

This is how the program works:

Entered number: 5


inserted: -858993460

inserted: -858993460

Answer Source

obj.rear1++ will return the current real1,

so in first time use

in >> obj.queue1[obj.rear1++]; becomes in >> obj.queue1[-1];

this is undefined behavior.

cout <<"inserted: " << obj.queue1[obj.rear1]; becomes cout <<"inserted: " << obj.queue1[0];

this read from uninitialized memory, also undefined behavior.

change obj.rear1++ to ++obj.rear1 can solve these two problem.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download