声明具有两种类型的变量:"int char"

Declaring a variable with two types: "int char"

我是 C++ 初学者,我正在阅读 Bjarne Stroustrup 的编程:使用 C++ 的原理和实践

3.9.2 不安全转换 部分,作者提到

When the initializer is an integer literal, the compiler can check the actual value and accept values that do not imply narrowing:

int char b1 {1000};     // error: narrowing (assuming 8-bit chars)

我对这个声明感到困惑。它使用两种类型(intchar)。我以前在Java和Swift(我比较熟悉的两种语言)中从来没有见过这样的声明。这是拼写错误还是有效的 C++ 语法?

书错了

标记序列 int char b1{1000}; 在语义上不是有效的 C++。

您正试图用不止一种类型声明 b1,这是没有意义的。

书中有误。这不是有效的 C++ 声明,即使没有所谓的缩小转换。

Bjarne Stroustrup's page(第 4 次印刷及更早版本)的任何勘误表中都没有提到它,这很奇怪。这是一个很明显的错误。我想因为它用 //error 评论,所以很少有人注意到声明本身的错误。

这是错误的。 在 C/C++ 中,可以通过使用联合来实现多类型声明。例如:

union {
    int i;
    char c;
} var;

var.i = 42;
/* OR */
var.c = ‘c’;

存储是相同的,所以 .c 和 .i 只是相同值的每个类型句柄。

这在 C/C++ 语法中是错误的。除了 unions(见@Alex 回答),还有一种 C++ 方法可以只存储一种可用类型,称为 std::variant(类型安全联合):

#include <variant>
#include <string>

int main()
{
    std::variant<int, float> v, w;
    v = 12; // v contains int
    int i = std::get<int>(v);
    w = std::get<int>(v);
    w = std::get<0>(v); // same effect as the previous line
    w = v; // same effect as the previous line

//  std::get<double>(v); // error: no double in [int, float]
//  std::get<3>(v);      // error: valid index values are 0 and 1

    try {
      std::get<float>(w); // w contains int, not float: will throw
    }
    catch (std::bad_variant_access&) {}

    std::variant<std::string> v("abc"); // converting constructors work when unambiguous
    v = "def"; // converting assignment also works when unambiguous
}