c++ - 如果加法表达式的第一个操作数可转换为指针和整数,选择哪种转换?

标签 c++ type-conversion overloading language-lawyer implicit-conversion

在下面的例子中,应该调用哪个转换函数?为什么要选择一个而不是另一个?

struct A
{
  operator int();
  operator int*();
};

A x;
int i = x + 1;

编译器选择 operator int().. 但为什么呢?

以下是 C++03 中的一些相关引述:

来自 [expr.add]

For addition, either both operands shall have arithmetic or enumeration type, or one operand shall be a pointer to a completely defined object type and the other shall have integral or enumeration type.

来自[转化]

expressions with a given type will be implicitly converted to other types in several contexts:

  • When used as operands of operators. The operator’s requirements for its operands dictate the destination type

最佳答案

此行为的原因是接受指针作为其左手操作数的内置运算符接受类型为 std::ptrdiff_t 的对象作为其右手操作数。这是在 C++11 标准的第 13.6 节中指定的:

For every cv-qualified or cv-unqualified object type T there exist candidate operator functions of the form

T * operator+(T *, std::ptrdiff_t);

[...]

由于 1 的类型为 int,编译器认为内置的 operator + 接受两个 int s 是更好的选择,因为它只需要对第一个参数进行(用户定义的)转换。

如果您提供类型为 std::ptrdiff_t 的参数作为 operator + 的右手操作数,您会看到预期的歧义:

int i = x + static_cast<std::ptrdiff_t>(1); // AMBIGUOUS!

这是一个live example .

关于c++ - 如果加法表达式的第一个操作数可转换为指针和整数,选择哪种转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17665110/

相关文章:

c++ - 使用 while 和 if 递归打印字符

c++ - 需要为单个解决方案Visual studio 2010的所有项目设置comman库文件

iphone - 将纬度/经度转换为度数/弧度?

scala - Scala 中的显式类型转换

C++ 将类的重载 operator() 作为函数指针传递

c++ - 我的 gloox 机器人有误

java - 字节数组转十六进制(int 格式)

C++从<<重载获取流修饰符

c# - C# .NET 中的重载方法

c++ - 使用 rxcpp 对聚合函数进行分组?