为什么我不能在这里使用三元运算符? [英] Why can't I use the ternary operator here?

查看:53
本文介绍了为什么我不能在这里使用三元运算符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此行将无法编译:

Shape shape = (i % 2) ? Circle(5) : Rectangle(5, 5);

(我知道这没用,因为无论表达式返回的内容如何,​​都将简化为简单的 Shape ,这不是重点).

(I know it's useless since whatever the expression returns will be reduced to a simple Shape, that's not the point).

无法弄清楚为什么它不能编译.我正在创建一个名为 shape Shape 变量(我认为这时会创建一个新的 Shape ),然后分配该变量变量表达式的结果.为什么不编译?

Can't figure out why it won't compile. I'm creating a Shape variable named shape (which I think at this point creates a new Shape), and then I'm assigning this variable the result of an expression. Why doesn't this compile?

错误:

no match for ternary operator

真正奇怪的是,具有相同含义的较长代码 可以按预期编译并运行:

What's really weird is that the longer code with exact same meaning does compile and run as expected:

    Shape shape;
    if (i % 2)
        shape = Rectangle(5, 5);
    else
        shape = Circle(5);

推荐答案

条件运算符的详细转换规则相当复杂(您可以在

The detailed conversion rules for the conditional operator are rather complex (you can find the full quote from the standard in this answer if you are interested). The short of it is that, when used with objects of class type, it will attempt to convert its second operand to match the type of the third, and its third operand to match the type of the second, but it won't try to convert both to a third class type.

由于 Circle 无法转换为 Rectangle ,并且 Rectangle 无法转换为 Circle ,因此编译器会抱怨(好吧,除非这两种类型定义了对指针的某种奇数转换,范围枚举或算术类型,在这种情况下,第5.16节[expr.cond]/p5起作用了.)

Since Circle isn't convertible to Rectangle and Rectangle isn't convertible to Circle, the compiler will complain (well, unless the two types define some odd conversion to pointer, scoped enumeration or arithmetic types, in which case §5.16 [expr.cond]/p5 comes into play).

还请注意,您的作业将对对象进行切片,而可能不是一个好主意.

Note also that your assignment will slice the object, which probably isn't a good idea.

这篇关于为什么我不能在这里使用三元运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆