是int{c}
另一种转换数据类型的方法吗?
是的。 T{value}
创建一个使用指定的括号T
初始化列表直接列表初始化的临时类型。这种强制转换确实有一个优势,可以用来创建一个临时数组。那会像T(value)
T{value}
int main() {
using int_array = int[5];
for( auto e : int_array{1,2,3,4,5})
std::cout << e;
}
它还附带一个警告,即缩小转换是一个错误
int main() {
int(10000000000ll); // warning only, still compiles
int{10000000000ll}; // hard error mandated by the standard
}
经过网上的一些研究,我知道 C++ 强制转换是不同的,它让编译器在编译时检查强制转换的可能性,但是 1 和 2 有什么区别?
T(value)
和之间的最大区别在于(T)value
in T(value)
,T
必须是一个单词。例如
int main() {
unsigned int(10000000); // error
(unsigned int)10000000; // compiles
}
Q3:还有其他方法可以显式转换/投射吗?
好吧,在 C++ 中,他们希望您使用 C++ 强制转换,即static_cast
、reinterpret_cast
、dynamic_cast
和const_cast
. 这些比 c 风格转换更受欢迎,因为 ac 风格转换将完成 C++ 版本具有某些限制并带有某些保证的所有那些。