C++ compiler error: ambiguous call to overloaded function

后端 未结 4 1583
-上瘾入骨i
-上瘾入骨i 2020-12-07 00:41
string aux;
int maxy,auxx=0;

cin>>aux;

maxy= (int)sqrt(aux.size());

I\'m geting:

1> error C2668: \'sqrt\' : ambiguous c         


        
4条回答
  •  被撕碎了的回忆
    2020-12-07 01:05

    The problem is that in C++, there are three functions named sqrt - one taking in a float, one taking a double, and one taking a long double. When you try calling

    sqrt(aux.size());
    

    The compiler tries to determine which of these functions you want to call. Since aux.size() returns a string::size_type, which is neither a float, double, nor long double, it tries to see if string::size_type is implicitly convertible to any of these three. But since string::size_type is convertible to all three of these types, the compiler marks the call as ambiguous, since it's unclear which of the conversions you want to do.

    To fix this, you can explicitly cast aux.size() to the type that you want. For example:

    sqrt(double(aux.size()));
    

    or

    sqrt(float(aux.size()));
    

    This makes the call unambiguously match one of the two functions. Depending on the precision you want, you can choose any of the three overloads. Since you're just casting back to an int, it's probably fine to cast to a float here.

提交回复
热议问题