c++ - 0 值的自动整数转换失败

标签 c++ integer implicit-conversion

我有这个源文件:

#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 overloadedA(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/

相关文章:

c++:虚拟性是否会跳过几代人?

c - GMP 库的整数乘法限制

javascript - 后效果 : Add prefix to result of an effect

scala - 隐式转换为Runnable?

c# - 使用策略模式在 C# 上实现类似行为的多参数 C++ 模板

c++ - 为什么 C++ 共享指针的行为不像迭代器的标准指针?

c++ - 奇怪的 Xcode 链接器警告构建 Poco C++ 应用程序

c++ - 关于隐藏成员变量的警告?

java - Generic 方法中的参数如何同时分配给 Integer 和 Character 类?

c++ - 为什么 `explicit` 关键字不能阻止 `char` 被转换为 `int` ?