三元运算符 [英] Ternary operator

查看:252
本文介绍了三元运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么逻辑原因会解释为什么在三元选择器中,两个分支必须具有相同的基本类型或可以转换为一个?没有这个规则的问题是什么?为什么我不能做这样的事情(这不是最好的例子,但澄清我的意思):

Is there any logical reason that will explain why in ternary optor both branches must have the same base type or be convertible to one? What is the problem in not having this rule? Why on earth I can't do thing like this (it is not the best example, but clarifies what I mean):

int var = 0;

void left();
int right();

var ? left() : right();


推荐答案

表达式必须在编译时知道类型。您不能有X或Y类型的表达式,它必须是一个或另一个。

Expressions must have a type known at compile time. You can't have expressions of type "either X or Y", it has to be one or the other.

考虑这种情况:

void f(int x) {...}
void f(const char* str) {...}

f(condition ? 5 : "Hello");

要调用哪种超负荷?这是一个简单的例子,有更复杂的例子。模板,它们必须在编译时知道。所以在上面的情况下,编译器不会根据条件选择一个重载,它必须选择一个重载来总是调用。

Which overload is going to be called? This is a simple case, and there are more complicated ones involving e.g. templates, which have to be known at compile time. So in the above case, the compiler won't choose an overload based on the condition, it has to pick one overload to always call.

它不能这样做,因此三元运算符的结果总是必须是相同类型(或兼容)。

It can't do that, so the result of a ternary operator always has to be the same type (or compatible).

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

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