overload of >> operator

Hi!

I've got some problems with overloading >> operator.

I need to write a class which will satisfy such test code:

1
2
3
4
5
6
7
8
stack S1, S2;
(...)
int a,b,c,d;

S1 >> a >> b;
S2 >> c;
S2 >> d;
(...)


and then print values of a,b,c,d. The idea is to pop back from the stack (implemented in class stack) int value to variable which states after >>.
I have written such overload of >> operator:

1
2
3
4
5
6
7
8
9
int operator >> (int &sink)
{
  if(content.empty())
  {
    sink = content.back();
    content.pop_back();
  }
  return sink;
}


The stack is implemented as a vector of int-s, which is called 'content'.

And now: what is the problem? The program prints out correctly values of a,c and d. Problem occurs with b, that is after the second pass of right shift operator.

The compiler says:

warning: value computed is not used
warning: 'b' may be used uninitialized in this function

I think, that something is wrong with my overloaded operator>>. But I've no idea how should I correct it :(

Thanks for your replies!



Look at the line S1 >> a >> b;. As for any operator, you could as well write ((S1 >> a) >> b);. Now, what is the result of S1 >> a? It's an integer, so the second >> is a simple shift operation. There is no reason to return an integer. You need the result of the first >> to be a stack, for the second >> to work. Change return type to stack& and return *this.
right! What was i thinking...

and now it's working perfectly :)

Thank you very much!
Quoting the FAQ-lite:
21.Don't overload an operator that is non-intuitive to your users. This is called the Doctrine of Least Surprise. For example, although C++ uses std::cout << x for printing, and although printing is technically called inserting, and although inserting sort of sounds like what happens when you push an element onto a stack, don't overload myStack << x to push an element onto a stack. It might make sense when you're really tired or otherwise mentally impaired, and a few of your friends might think it's "kewl," but just say No.

(Source: http://www.parashift.com/c++-faq-lite/operator-overloading.html#faq-13.9 )

Your own choice, of course, but I personally find "pop" and "push" much easier to understand, especially since they're named that way for nearly every basic data structure. Also, I think I might have a serious case of angled-brackets-dyslexia.
Topic archived. No new replies allowed.