c++ - 在 C++ 中,我们可以使用 { } 进行 C 风格转换吗?

标签 c++ casting type-conversion explicit-conversion

当我一直在阅读数据类型转换时,我看到了这个例子:

void intval()
{
    for (char c; cin >> c; )
    cout << "the value of '" << c << "' is " << int{c} << '\n';
}

我知道我们可以使用:

  1. int(c)
  2. (int) c
  3. 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_castreinterpret_castdynamic_castconst_cast。这些优于 c 样式转换,因为 c 样式转换将执行所有 C++ 版本具有某些限制并具有某些保证的操作。

关于c++ - 在 C++ 中,我们可以使用 { } 进行 C 风格转换吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42975620/

相关文章:

casting - 快速子类和类型转换

php - 如何在 MySQL 或 PHP 中将 32 位整数从无符号转换为有符号?

python - 如何将列表中的元素连接到 Python 中的一个变量中?

c++ - 如何使用 C++ 测量 Linux 中切换进程上下文的时间?

c++ - 可以更改模板参数吗?

c++ - 尝试编译C++代码时出现歧义错误

c++ - 编译器是否避免中间整数提升或转换?

c++ - 数组声明为 unsigned char 时的垃圾值

type-conversion - 将LESS中的rgba颜色定义字符串转换为颜色实例

c++ - 在 Windows 上,什么时候需要附加到目录路径才能使 _stat 成功?