compile error - operator overloading

L

Laxman

==C.H <==
#include <fstream.h>
class C
{
public:
C(int i);
friend ofstream& operator<<(ofstream& os, const C&);
};
------------------------------------------------------------
==B.H <==
#include <fstream.h>
#include "C.H"

class B
{
public:
friend ofstream& operator<<(ofstream& os, const B&);
};
------------------------------------------------------------
==B.C <==
#include "B.H"

ofstream& operator<<(ofstream& os, const B& b)
{
int i = 1;
os << i;
return os;
}
------------------------------------------------------------
CC -c B.C
"B.C", line 6: Error: Overloading ambiguity between
"std::basic_ostream<char, std::char_traits<char>>::eek:perator<<(int)"
and "operator<<(std::basic_ofstream<char, std::char_traits<char>>&,
const C&)"

To make it easier I have trimmed down and kept only the necessary
code
to create the error.
BTW this works fine with g++ but fails with Sun Forte Compiler.
Any idea what the problem is ?
 
L

Laxman

MiniDisc_2k2 said:
This may be unstandardized, I'm not sure, but I can tell you what the
problem is.
Your class C has a constructor which takes a parameter of an integer. Thus,
i can be converted to a C if necessary. There is automatically an operator
<< for ofstream which takes an int, but you're also defining one which takes
a C. As an int can be readily converted to a C, the compiler gets confused
as to which one you want. A C cannot be converted to an int, so perhaps the
solution is to cast it to a C. Also, perhaps explicitly typecasting it to an
int would resolve the ambiguity to the compiler (even though it already is
an int).
Thanks for replying. I did try to cast it explicitly to int but with
no luck!!

In the above example, I am trying to print a random datatype (int) but
my intent is to print a data member of B which is actually another
class, say A and C takes that same A as constructor's parameter.
 
L

Laxman

Steve Pinard said:
class C
{
C(int i)
...
};

As posted, declaring the constructor this way allows implicit conversion of
an int to a C. This is usually NOT what you want the compiler to do for
you, and is the source of some hard-to-track-down problems (case in point?).

For constructors with only one parameter, I almost always use "explicit" to
prevent the compiler from doing that:

class C
{
explicit C(int i)
...
};

Have to credit Scott Meyers for this. I learned it from one of his
Effective C++ books.

--
Steve Pinard

"Dr. Spock is the only Star Wars character I know"
- My Mom

Thanks Steve. It works!!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,995
Messages
2,570,233
Members
46,821
Latest member
AleidaSchi

Latest Threads

Top