我有这个源文件:
#include <ctime>
class A
{
public:
A(unsigned long i){};
A(const tm*){};
};
int main(int argc, char** argv)
{
A tit(1);
A tat(0);
return 0;
}
当我使用 gcc 3.4.2 编译它时,我得到以下结果:
autoCast.cpp: In function
int main(int, char**)':<br/> autoCast.cpp:13: error: call of overloaded
A(int)' is ambiguous
autoCast.cpp:4: note: candidates are: A::A(const A&)
autoCast.cpp:7: note: A::A(const tm*)
autoCast.cpp:6: note: A::A(long unsigned int)
我的问题是:为什么创建 A tit(1)
(第 12 行)成功,而 A tat(0)
(第 13 行)失败?我在这些行中尝试了不同的参数类型(例如 0ULL 和 1ULL),但当参数值为 0 时它总是失败,而当参数值为 1 时它会成功。唯一不引发错误的 0 值是 0UL(因为没有我猜需要转换)。为什么在这种情况下,值为 0 的整数与值为 1 的整数会得到不同的处理?它与 time.h 中定义的 tm 结构体有关吗?
最佳答案
这是因为 0
是一个空指针常量,并且可以转换为unsigned long或指针,因此使用哪个是不明确的选择。 C++ 标准草案 4.10
指针转换 说(强调我的):
A null pointer constant is an integral constant expression (5.19) prvalue of integer type that evaluates to zero or a prvalue of type std::nullptr_t. A null pointer constant can be converted to a pointer type; the result is the null pointer value of that type and is distinguishable from every other value of object pointer or function pointer type.
而1
不是空指针常量。虽然 0UL
也可以转换为指针,但它更适合 unsigned long 构造函数,因为不需要转换。
关于c++ - 0 值的自动整数转换失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21431868/