Visual Studio C ++对重载函数的模糊调用

时间:2011-12-23 16:34:13

标签: c++ visual-studio-2010 inheritance operators

编辑:我发布了全班(为了错误无关紧要的事情,条纹了一些)

我做了以下课程:

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;
};

1 个答案:

答案 0 :(得分:3)

如果错误确实发生在您尝试将函数结果分配给新变量的位置,则问题可能是您的复制构造函数。您应该在packet&中创建const,以便它可以与临时对象一起使用:

packet(const packet & text, int length=-1);

如果您的类可以隐式转换为intfloat,那么其他构造函数可能会起作用。

由于此类问题,通常建议不要添加不必要的转换运算符并将构造函数标记为explicit,以避免意外的隐式转换。