铸造:btw有什么区别。(Casting: What is the difference btw. T(value) and (T)value for built

编程入门 行业动态 更新时间:2024-10-23 03:15:11
铸造:btw有什么区别。(Casting: What is the difference btw. T(value) and (T)value for built-in types? [duplicate])

可能重复: C ++演员语法样式 (类型)值和类型(值)之间有什么区别?

在C ++中,当显式地将一个内置类型转换为另一个内置类型时,您可以编写:

int x = (int)c; int x = int(c); int d = (double)f; int d = double(f);

我知道(T)v是一个C风格的演员,我认为其他语法在技术上不是演员,但是其他语法是什么,它的语义是什么? (以及在哪里使用?)

Possible Duplicates: C++ cast syntax styles What is the difference between (type)value and type(value) ?

In C++, when explicitly converting one built-in type to another, you can write:

int x = (int)c; int x = int(c); int d = (double)f; int d = double(f);

I known that (T)v is a C-style cast, and I think the other syntax isn't technically a cast, but what is the other syntax called and what are its semantics? (And where to use which?)

最满意答案

T(value)实际上是类型T的初始化,并且因为它是初始化,所以如果value的类型和T是可转换的,则可以发生隐式类型转换。 如果T是一个类对象,则调用其中一个构造函数,或者采用单个值的默认构造函数, T和value是可隐式转换类型,或者复制构造函数具有两个类型可隐式转换的相同条件。 正如您所指出的, (T)value是从value类型到类型T的C样式转换。 最后两者虽然如此,但在引擎盖下却几乎都做同样的事情

T var1 = T(value); T var2 = (T)value;

你得到完全相同的结果,即创建/返回类型为T的对象,用于初始化类型为T的l值。

T(value) is actually an initialization of the type T, and because it's an initialization, an implicit type conversion can take place if the type of value and T are convertible. If T is a class-object, then one of it's constructors is called, either a default constructor that takes a single value and T and value are implicitly convertible types, or the copy constructor with the same condition that the two types are implicitly convertible. (T)value, as you've noted, is a C-style cast from the type of value, to the type T. Both in the end though are pretty much doing the same thing under the hood since if you did

T var1 = T(value); T var2 = (T)value;

you'd get the exact same result, that is both create/return an object of type T which an be used to initialize an l-value of type T.

更多推荐

本文发布于:2023-08-06 17:14:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1453812.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:有什么区别   btw   Casting   built   difference

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!