4

So let's say I have the following class :

namespace Example
{
    class Bar {};
}

Now in case I want to overload the operators for the class Bar, should I do :

 namespace Example
 {
    class Bar {};

    ostream& operator<<(ostream& os, const Bar& b)
    {/*..........*/}
}

or should I do :

namespace Example
{
    class Bar {};
}

ostream& operator<<(ostream& os, const Example::Bar& b)
{/*..........*/}

If I'm supposed to do either of the above, please post the explanation for why it should be done that way.

P.S. /*.....*/ simply means the body of the functions(omitted for simplicity)

juanchopanza
  • 223,364
  • 34
  • 402
  • 480
J.Alvaro.T
  • 138
  • 2
  • 2
  • 12
  • Also possibly of interest: http://stackoverflow.com/questions/5195512/namespaces-and-operator-resolution – anderas Jul 28 '15 at 13:17
  • @Petr IMO, no mine isn't a duplicate. In the link you gave it told me to do it in the namespace because the compiler would find it. But, the thing I"m asking is if either is better and why? Thank you for the link though – J.Alvaro.T Jul 28 '15 at 13:18
  • @J.Alvaro.T, it also says "No need to pollute the global namespace". And other answers there say the same ("...and not to clutter the global namespace.") – Petr Jul 28 '15 at 13:19
  • @Petr Thank you for pointing that out. Probably missed it. Sometimes I just skim through a question and missed the important parts. – J.Alvaro.T Jul 28 '15 at 13:21

1 Answers1

-2
  #include<iostream>
  using namespace std;

    namespace Example
     {
        class Bar
        {//........

friend ostream& operator<<(ostream& os, const Bar& b);
};


    }

    ostream& operator<<(ostream& os, const Example::Bar& b)
        {//..........
        }

    int main() {
        Example :: Bar b;
//        out<<b;  I am not sure About this 
        return 0;
    }

Hope I did well this time

Bhavesh Kumar
  • 116
  • 1
  • 9