在下面的例子中,应该调用哪个转换函数?为什么要选择一个而不是另一个?
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/