【发布时间】:2015-08-27 13:59:22
【问题描述】:
三元运算符的参数有隐式类型转换的规则吗?
三元运算符总是需要返回相同的类型。此类型仅由第二个和第三个参数 (1st ? 2nd : 3rd) 确定,因此两个参数都转换为此类型。这种类型是如何确定的?
更具体地说,我测试了一个例子:
class pointclass
{
pointclass();
pointclass( int i ); // (pointclass)(int)
operator bool() const; // (bool)(pointclass)
};
我有一个类 (pointclass),它支持从 int 到 pointclass 的隐式转换以及从 pointclass 到 bool 的隐式转换。
int i;
pointclass p;
bool b;
b ? p : i; // (bool) ? (int)(bool)(pointclass) : (int)
b ? i : p; // (bool) ? (int) : (int)(bool)(pointclass)
使用三元运算符,我比较pointclass 和int。编译器使用从pointclass 到bool 的隐式转换,然后使用从bool 到int 的标准转换。无论我是否交换第二个和第三个参数,这都完成了。 为什么不能将int 转换为pointclass?
使用比较运算符要简单得多:
p == i; // (pointclass) == (pointclass)(int)
i == p; // (int) == (int)(bool)(pointclass)
参数的类型仅由第一个参数确定。
但是我不明白三元运算符的类型转换规则。对我来说,这似乎就像使用大多数转换的方式。
【问题讨论】:
-
是的,规则在标准的[expr.cond]中。
-
比我更精通标准方式的人可以给出权威的答案,但根据经验,它们会转换为可以转换为的“最接近”的常见类型。
-
如果你认为 C++ 做的事情很时髦,请想想那些可怜的 Java 人。
-
规则在 5.16 [expr.cond] 中列出。哪一个有问题?
-
问题是转换为bool,它丢弃了几乎所有的信息。最好的方法是防止从 bool 成功进行隐式转换。
标签: c++ types implicit ternary