編譯器錯誤 C2666

'identifier' :數位多載具有類似的轉換

多載函式或運算子模棱兩可。 正式參數清單可能太類似,編譯器無法解析模棱兩可。 若要解決此錯誤,請明確轉換一或多個實際參數。

範例

下列範例會產生 C2666:

// C2666.cpp
struct complex {
   complex(double);
};

void h(int,complex);
void h(double, double);

int main() {
   h(3,4);   // C2666
}

由於 Visual Studio 2019 16.1 版已完成的編譯器一致性工作,可能會產生此錯誤:

  • 如果兩者不同,則升級列舉的轉換,其基礎型別固定為其基礎類型,比升階為升級基礎類型的轉換更好。

下列範例示範如何在 Visual Studio 2019 16.1 版和更新版本中變更編譯器行為:

#include <type_traits>

enum E : unsigned char { e };

int f(unsigned int)
{
    return 1;
}

int f(unsigned char)
{
    return 2;
}

struct A {};
struct B : public A {};

int f(unsigned int, const B&)
{
    return 3;
}

int f(unsigned char, const A&)
{
    return 4;
}

int main()
{
    // Calls f(unsigned char) in 16.1 and later. Called f(unsigned int) in earlier versions.
    // The conversion from 'E' to the fixed underlying type 'unsigned char' is better than the
    // conversion from 'E' to the promoted type 'unsigned int'.
    f(e);
  
    // Error C2666. This call is ambiguous, but previously called f(unsigned int, const B&). 
    f(e, B{});
}

這個錯誤也可能因為針對 Visual Studio .NET 2003 完成的編譯器一致性工作而產生:

  • 二元運算子和使用者定義對指標類型的轉換

  • 資格轉換與身分識別轉換不同

對於二元運算子 < 、 、 <> = 和 > =,如果參數的類型定義使用者定義轉換運算子,則傳遞的參數現在會隱含轉換成運算元的類型。 現在有模棱兩可的可能性。

對於 Visual Studio .NET 2003 和 Visual Studio .NET 版本的 Visual C++ 中有效的程式碼,請使用函式語法明確呼叫 類別運算子。

// C2666b.cpp
#include <string.h>
#include <stdio.h>

struct T
{
    T( const T& copy )
    {
        m_str = copy.m_str;
    }

    T( const char* str )
    {
        int iSize = (strlen( str )+ 1);
        m_str = new char[ iSize ];
        if (m_str)
            strcpy_s( m_str, iSize, str );
    }

    bool operator<( const T& RHS )
    {
        return m_str < RHS.m_str;
    }

    operator char*() const
    {
        return m_str;
    }

    char* m_str;
};

int main()
{
    T str1( "ABCD" );
    const char* str2 = "DEFG";

    // Error - Ambiguous call to operator<()
    // Trying to convert str1 to char* and then call
    // operator<( const char*, const char* )?
    //  OR
    // trying to convert str2 to T and then call
    // T::operator<( const T& )?

    if( str1 < str2 )   // C2666

    if ( str1.operator < ( str2 ) )   // Treat str2 as type T
        printf_s("str1.operator < ( str2 )\n");

    if ( str1.operator char*() < str2 )   // Treat str1 as type char*
        printf_s("str1.operator char*() < str2\n");
}

下列範例會產生 C2666

// C2666c.cpp
// compile with: /c

enum E
{
    E_A,   E_B
};

class A
{
    int h(const E e) const {return 0; }
    int h(const int i) { return 1; }
    // Uncomment the following line to resolve.
    // int h(const E e) { return 0; }

    void Test()
    {
        h(E_A);   // C2666
        h((const int) E_A);
        h((int) E_A);
    }
};