这段代码在 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/