选角:顺便说一句,有什么区别。内置类型的 T(value) 和 (T)value?
可能的重复:
C++ 转换语法样式
(type)value 和 type(value) 之间有什么区别?< /a>
在 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?)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
T(value)
实际上是类型T
的初始化,并且由于它是初始化,因此如果value
的类型可以发生隐式类型转换code> 和T
是可以转换的。如果T
是类对象,则调用它的构造函数之一,可以是采用单个值的默认构造函数以及T
和value
是隐式可转换类型,或者是复制构造函数,条件相同,即这两种类型是隐式可转换的。正如您所注意到的,(T)value
是从value
类型到T
类型的 C 风格转换。但最终两者都在幕后做着同样的事情,因为如果你这样做了,你会得到完全相同的结果,那就是都创建/返回一个可以使用的
T
类型的对象初始化T
类型的左值。T(value)
is actually an initialization of the typeT
, and because it's an initialization, an implicit type conversion can take place if the type ofvalue
andT
are convertible. IfT
is a class-object, then one of it's constructors is called, either a default constructor that takes a single value andT
andvalue
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 ofvalue
, to the typeT
. Both in the end though are pretty much doing the same thing under the hood since if you didyou'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 typeT
.