[英]If I want to promote a char to an int, should I use static_cast<int>(char variable) or +(char variable) and why?
This question is a little subjective, but I believe it may lead to some constructive answers. 这个问题有点主观,但我相信它可能会带来一些建设性的答案。 Assume I have char x;
假设我有char x;
and I want to promote it to an integral so I can access it's numeric value. 我想将其提升为整数,以便可以访问其数值。 Which should I prefer to use and why? 我更喜欢使用哪个?为什么? static_cast<int>
or unary arithmetic operator +
? static_cast<int>
或一元算术运算符+
?
My own thoughts are that using a static_cast<int>
is more explicit and readable. 我自己的想法是使用static_cast<int>
更明确和可读。 However, using the unary arithmetic operator +
is shorter code. 但是,使用一元算术运算符+
是较短的代码。
Is one way safer than the other? 一种方法比另一种安全吗?
IMO, there is one important advantage of using static_cast
, even if it is a little bit more verbose: it allows you to quickly search your code for casts via grep
or any other text searching utility. IMO,使用static_cast
有一个重要优点,即使它有些冗长:它也使您可以通过grep
或任何其他文本搜索实用程序快速在代码中搜索强制类型转换。 In large projects this may make the difference, since otherwise C-style casts are often mistakenly matched in functions declarations such as void f(double)
, where (double)
is of course not a cast. 在大型项目中,这可能会有所不同,因为否则,C型强制转换通常会在函数声明中错误地匹配,例如void f(double)
,其中(double)
当然不是强制转换。
Moreover, static_cast
makes perfectly clear your intention. 此外, static_cast
可以清楚地表明您的意图。 Using the +
operator may seem exotic (incomprehensible) to someone who is not 100% familiar with integer promotions rules. 对于不是100%熟悉整数促销规则的人,使用+
运算符似乎很奇怪(难以理解)。 In terms of "safety", afaik, both are equally good. 在“安全性”方面,afaik都同样出色。
Related: What is the difference between static_cast<> and C style casting? 相关: static_cast <>和C样式转换之间有什么区别?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.