Edit: I posted the whole class (striped a few for the error irrelevant things out)
I made following class:
class packet
{public:char * buffer;
int size;
int data;
packet();
packet(packet &text, int length=-1);
packet(char * text, int length=-1);
packet(int val);
packet(char c);
packet(double d);
packet(float f);
~packet();
packet & operator= (packet &text);
packet operator+ (packet &text);
packet & operator+= (packet &text);
packet & operator|= (packet &text);
bool operator== (packet &text);
bool operator*= (packet &text);
bool operator!= (packet &text);
operator char* () const;
operator int () const;
operator float () const;
char operator [] (int pos) const;
};
And I use the class like this:
packet p = packet();
or
return packet();
And Visual Studio gives me this error:
test.cpp(162): error C2668: 'packet::packet' : ambiguous call to overloaded function
...packet.h(26): could be 'packet::packet(float)'
...packet.h(23): or 'packet::packet(int)'
...packet.h(22): or 'packet::packet(char *,int)'
Does anyone know what I am doing wrong here ? Why is this ambigous ?
PS: I think it has to do with the 4 operators at the bottom but I am a little hazy with overloading those kind of operators…
Solution: I got it working by marking some constructors as explicit:
class packet
{public:char * buffer;
int size;
int data;
packet();
packet(packet &text, int length=-1);
explicit packet(char * text, int length=-1);
explicit packet(int val);
explicit packet(char c);
explicit packet(double d);
explicit packet(float f);
~packet();
packet & operator= (packet &text);
packet operator+ (packet &text);
packet & operator+= (packet &text);
packet & operator|= (packet &text);
bool operator== (packet &text);
bool operator*= (packet &text);
bool operator!= (packet &text);
operator char* () const;
operator int () const;
operator float () const;
char operator [] (int pos) const;
};
In case the error really occurs at the place where you try to assign the result of the function to a new variable, the problem could be your copy constructor. You should make the
packet&inconstso that it can be used with temporary objects:The other constructors might come into play in this case if your class is implicitly convertible to
int,float,….Due to such issues it is usually advisable to not add unnecessary conversion operators and mark constructors as
explicitto avoid unexpected implicit conversions.