使用条件if else运算符初始化参考变量 [英] Initializing reference variables with the conditional if else operator

查看:74
本文介绍了使用条件if else运算符初始化参考变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下C ++无效,因为引用变量需要初始化程序:

The following C++ is invalid because reference variables require initializers:

int& a; // illegal
if (isfive) {
  a = 5;
} else {
  a = 4;
}

但是,MSVC似乎认为这还可以:

However, MSVC seems to think this is okay:

int& a = isfive ? 5 : 4;

对我而言,这意味着MSVC实际上将条件运算符视为单个表达式,而没有将其扩展为

This implies to me that MSVC is actually treating the conditional operator like a single expression and not expanding it into an if-else statement.

使用条件运算符初始化引用始终是有效的C ++吗?

Is it always valid C++ to initialize a reference using the conditional operator?

推荐答案

MSVC具有非标准的扩展名。这意味着它允许破坏代码。

MSVC has a non-standard "extension". What it means is that it allows broken code. There's a good reason this is prohibited.

还请注意

int& a = 5;

在标准C ++中也不合法。

is not legal in Standard C++ either.

但是,通常,使用任何可以转换为正确类型(包括使用条件运算符)的表达式初始化 const 引用是合法的。用合法类型的左值初始化非 const 引用是合法的,条件运算符在某些条件下会产生该值。

In general, though, it is legal to initialize a const reference with any expression which can be converted to the right type (including use of the conditional operator). And it is legal to initialize a non-const reference with an lvalue of the right type, which the conditional operator yields under certain conditions.

这篇关于使用条件if else运算符初始化参考变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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