c++ - 为什么函数重载不会导致歧义错误? (c++)

标签 c++ function overloading implicit-conversion

这段代码在 gcc 4.6.1 和 4.8.1 中编译没有错误(eclipse auto compilation says: Candidates are: float pow(float, int) long double pow(long double, int) double pow(double, int) ):

#include <iostream>
#include <cmath>
#include <vector>
using namespace std;

int main(void) {
    const int i = 0, x = 2;
    double y = pow( i, x );
    y = log( i ) / log( x );
    cout << y;
return 0;
}

非常感谢。这段代码在工作中造成了一些混淆。编译器可信吗?

最佳答案

您不会遇到任何编译错误,因为 C++ 标准规定您的整数类型将被接受并转换为 double 类型。

来自标准 §26.8/11:

Moreover, there shall be additional overloads sufficient to ensure:
[...]
3. Otherwise, if any argument corresponding to a double parameter has type double or an integer type, then all arguments corresponding to double parameters are effectively cast to double.

另见 cppreference.com/.../pow它说:

If any argument has integral type, it is cast to double.

关于c++ - 为什么函数重载不会导致歧义错误? (c++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17264811/

相关文章:

C++ 动态库段错误

c++ 在 switch 语句中使用 cin

在 C 中调用以字符串变量命名的函数

jquery - 从另一个js文件调用 channel 连接函数

c++ - 重载运算符 << - 必须是二元运算符

C++ 检查单例指针

c++ - 插入到 std::unordered_multimap 时有没有办法避免散列/equalityChecking?

php - INSERT INTO & LAST_INSERT_ID inside Query inside 函数

c++ - 构建 "OpenSubdiv"时错误重载具有类似的转换

c++ - 模板函数重载