Home
Fractals
Tutorials
Books
Archive
My blog
My LinkedIn Profile

BOOKS i'm reading

Cryptography engineering, Niels Ferguson, Bruce Schneier, Tadayoshi Kohno, ISBN: 9780470474242
Advanced Programming in the UNIX(R) Environment (2nd Edition), W. Richard Stevens, Stephen A. Rago, ISBN:0201433079
Trading For a Living, Alexander Elder, ISBN:0471592242

mailto:olivier@olivierlanglois.net

operator<< for a private inner class

04/12/08

Permalink 09:04:01 am, by lano1106 Email , 279 words, 167 views   English (CA)
Categories: C++

operator<< for a private inner class

Suppose we have

class A
{
  private:
  class B
  {
  };
};

and we would like to define operator<< for class B. I had this situation yesterday and it took me few tries to make it work. I first tried:

class A
{
...
};
std::ostream operator<<( ostream &, const A::B & );

It did not work because the compiler complained that B was private. My second attempt:

class A
{
  private:
  class B
  {
  };
  static std::ostream &operator<<( ostream &, const B & );
};

I was getting closer to the solution but this was still not quite right. Apparently, you do not have the right to declare operator<< as a static member of another class or as soon as an operator is defined as a class member, automatically, the compiler expect the left operand to be of this class type.

Then I tried this:

class A
{
  private:
  class B
  {
  };
  friend std::ostream &operator<<( ostream &, const B & );
};
std::ostream &operator<<( ostream &o, const A::B &b )
{
}

This time, I am not sure why but the linker now was complaining about duplicate symbols for my operator<< function. Not sure if it is the code that has a problem. It looks good to me. I suspect that maybe it is parameter type mangling problem and the compiler does not recognize 'const B &' as the same as 'const A::B &' but anyhow, I did not pursue the investigation I have finally made the code work like this:

class A
{
  private:
  class B
  {
  };
  friend std::ostream &operator<<( ostream &o, const B &b )
  {
  }
};

Comments, Pingbacks:

No Comments/Pingbacks for this post yet...

Leave a comment:

Your email address will not be displayed on this site.
Your URL will be displayed.

Allowed XHTML tags: <p, ul, ol, li, dl, dt, dd, address, blockquote, ins, del, span, bdo, br, em, strong, dfn, code, samp, kdb, var, cite, abbr, acronym, q, sub, sup, tt, i, b, big, small>
(Line breaks become <br />)
(Set cookies for name, email and url)
(Allow users to contact you through a message form (your email will NOT be displayed.))

Olivier Langlois's blog

I want you to find in this blog informations about C++ programming that I had a hard time to find in the first place on the web.

February 2012
Sun Mon Tue Wed Thu Fri Sat
 << <   > >>
      1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29      

Search

Custom Search

XML Feeds

What is RSS?

Who's Online?

  • Guest Users: 5

powered by
b2evolution