8

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

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++强制转换是不同的,它有编译器在编译时检查强制转换的可能性,但是1和2有什么区别?int{c}如果只是另一种铸造方式, 又有什么不同呢?

Q3:还有其他方法可以显式转换/投射吗?

4

3 回答 3

10

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)valuein T(value),T必须是一个单词。例如

int main() {
    unsigned int(10000000); // error
    (unsigned int)10000000; // compiles
}

Q3:还有其他方法可以显式转换/投射吗?

好吧,在 C++ 中,他们希望您使用 C++ 强制转换,即static_castreinterpret_castdynamic_castconst_cast. 这些比 c 风格转换更受欢迎,因为 ac 风格转换将完成 C++ 版本具有某些限制并带有某些保证的所有那些。

于 2017-03-23T12:49:19.880 回答
6

int(c)是 C-style cast 的 C++ 版本(int)c。它首先尝试 a const_cast<int>(c),然后(失败) a ,static_cast<int>(c)然后是reinterpret_cast

int{c}是一壶稍有不同的鱼。严格来说,这是列表初始化,并且有更严格的规则。特别是不允许缩小转换,即

int x;
char s{x};  // error

因此,除非您知道缩小转换是可以接受的,否则建议使用它(而不是强制转换)。

除了内置类型之外,除了上面提到的强制转换之外,还有dynamic_cast.

于 2017-03-23T12:44:46.780 回答
3

Q1:是的。它与函数式风格转换 () 几乎相同int(c),并且由于 c++11 的统一初始化而起作用。但是大括号初始化确实有一些注意事项,例如缩小转换(如long l = 5; char c{l};)会产生警告。

Q2:1 和 2 是等价的,尽管在某些情况下一个有效,另一个无效。

// long long(c); // Breaks unless you make a typedef for 'long long'
(long long)c;    // Works fine

template <class In, class Out>
Out convert(const In& in) {
    // return (Out)in; // Only works if 'In' is a primitive type
    return Out(in);    // Works regardless of the type of 'In' (assuming an appropriate constructor exists)
}

Q3:你提到的 C++ 风格转换的唯一例子是static_cast. 还有其他 C++ 类型转换:

  • dynamic_cast
  • reinterpret_cast
  • const_cast
于 2017-03-23T12:35:06.827 回答