当我一直在阅读数据类型转换时,我看到了这个例子:
void intval()
{
for (char c; cin >> c; )
cout << "the value of '" << c << "' is " << int{c} << '\n';
}
我知道我们可以使用:
-
int(c)
-
(int) c
-
static_cast<int>(c)
我的问题:
Q1:是int{c}
另一种转换数据类型的方法?
Q2:在网上查了一下,我知道C++的casting是不同的,它让编译器在编译时检查casting的可能性,但是1和2有什么区别?以及如何int{c}
如果它只是另一种类型转换方式会有所不同吗?
Q3:还有其他显式转换/转换的方法吗?
最佳答案
Is
int{c}
another way of casting data types?
是的。 T{value}
创建一个 T
类型的临时对象,它是 direct-list-initialized 具有指定的 braced-init-list。此转换确实优于 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
}
After some research on the net, I know that C++ casting is different and it have the compiler check the casting possibility at the compile time, but what are the differences between 1 and 2?
T(value)
和(T)value
最大的区别在于,在T(value)
中,T
必须是一个单词。例如
int main() {
unsigned int(10000000); // error
(unsigned int)10000000; // compiles
}
Q3: Are there any other ways to explicitly convert/cast?
在 C++ 中,他们希望您使用 C++ 强制转换,它们是 static_cast
、reinterpret_cast
、dynamic_cast
和 const_cast
。这些优于 c 样式转换,因为 c 样式转换将执行所有 C++ 版本具有某些限制并具有某些保证的操作。
关于c++ - 在 C++ 中,我们可以使用 { } 进行 C 风格转换吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42975620/