可能重复: 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.
更多推荐
发布评论