编辑:我张贴了整个类(条纹一些错误无关的东西出来)
我创建了以下类:
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;
};
我这样使用这个类:
packet p = packet();
或
return packet();
和Visual Studio给了我这个错误:
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)'
有人知道我在这里做错了什么吗?为什么会有歧义?
PS:我认为这与底部的4个操作符有关,但我对重载这些操作符有点模糊…
解决方案:我通过将一些构造函数标记为显式来使其工作:
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;
};
如果错误确实发生在您尝试将函数结果赋值给新变量的地方,问题可能是您的复制构造函数。您应该将packet&
放在const
中,以便它可以用于临时对象:
packet(const packet & text, int length=-1);
如果您的类可以隐式转换为int
, float
,....
由于这些问题,通常建议不要添加不必要的转换操作符,并将构造函数标记为explicit
,以避免意外的隐式转换。