Tho*_*hor 80 c++ initialization type-conversion narrowing uniform-initialization
我是C++初学者,我正在阅读Bjarne Stroustrup的编程:使用C++的原理和实践.
在3.9.2"不安全转换 "一节中,作者提到了
当初始化程序是整数文字时,编译器可以检查实际值并接受不暗示缩小的值:
Run Code Online (Sandbox Code Playgroud)int char b1 {1000}; // error: narrowing (assuming 8-bit chars)
我对这个宣言感到困惑.它使用两种类型(int和char).我以前从未在Java和Swift中看过这样的声明(我比较熟悉的两种语言).这是拼写错误还是有效的C++语法?
Sto*_*ica 94
这本书是个错误.这不是一个有效的C++声明,即使没有假设的缩小转换.
在Bjarne Stroustrup的页面(第4次印刷及更早版本)的任何一个错误中都没有提及,但这很奇怪.这是一个明显的错误.我想,因为它被注释,//error很少有人注意到声明本身的错误.
Ale*_*lex 10
这是错误的.在C/C++中,可以通过使用联合来实现多类型声明.例如:
union {
int i;
char c;
} var;
var.i = 42;
/* OR */
var.c = ‘c’;
Run Code Online (Sandbox Code Playgroud)
存储是相同的,因此.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
}
Run Code Online (Sandbox Code Playgroud)