如何修复隐式转换的 C++ 警告?
How to fix C++ warning of implicit conversion?
我刚刚开始使用 C++。
我正在尝试获取字符串 'str' 的前三个字符,并将其与已知字符串进行比较,例如 'knownString'。
为此,我编写了这行代码:
if (str.substr(start, 3) == knownString)
其中 'start' 是我之前声明的整数。
但我不断收到此警告消息:
warning: implicit conversion changes signedness: 'int' to
'std::__cxx11::basic_string,**
**std::allocator >::size_type' (aka 'unsigned int')
有谁知道我可以添加或遗漏的内容来解决此问题?
This warning is triggered by the -Wsign-conversion
switch,检测到您正在使用一个有符号变量并将其转换为一个无符号变量,这种方式可能会改变值。
它不会对正文字执行此操作,其中转换显然不会更改值,因为那将毫无意义且非常烦人。你会得到像 -5
.
这样的否定文字
(从技术上讲,这是应用了一元否定运算符的文字 5
,而不是 "negative literal"!)。
对于命名变量,它无法真正预测值是多少,所以谨慎行事。
您应该使变量 start
的类型为 size_t
。
您可以:
要么 1. 明确转换:
str.substr(static_cast<std::string::size_type>(start), 3)
或者2.一开始就不做转换:
std::string::size_type start;
或者 3. 要求编译器不要警告它:
g++ compilation arguments -Wno-sign-conversion
我推荐选项 2。
我刚刚开始使用 C++。
我正在尝试获取字符串 'str' 的前三个字符,并将其与已知字符串进行比较,例如 'knownString'。
为此,我编写了这行代码:
if (str.substr(start, 3) == knownString)
其中 'start' 是我之前声明的整数。 但我不断收到此警告消息:
warning: implicit conversion changes signedness: 'int' to 'std::__cxx11::basic_string,** **std::allocator >::size_type' (aka 'unsigned int')
有谁知道我可以添加或遗漏的内容来解决此问题?
This warning is triggered by the -Wsign-conversion
switch,检测到您正在使用一个有符号变量并将其转换为一个无符号变量,这种方式可能会改变值。
它不会对正文字执行此操作,其中转换显然不会更改值,因为那将毫无意义且非常烦人。你会得到像 -5
.
(从技术上讲,这是应用了一元否定运算符的文字 5
,而不是 "negative literal"!)。
对于命名变量,它无法真正预测值是多少,所以谨慎行事。
您应该使变量 start
的类型为 size_t
。
您可以:
要么 1. 明确转换:
str.substr(static_cast<std::string::size_type>(start), 3)
或者2.一开始就不做转换:
std::string::size_type start;
或者 3. 要求编译器不要警告它:
g++ compilation arguments -Wno-sign-conversion
我推荐选项 2。