运行这段代码:
#include <string>
#include <iostream>
using namespace std;
int main() {
string a = "Hello, world!";
cout << (-1)*a.size() << endl;
}
Run Code Online (Sandbox Code Playgroud)
我得到:
18446744073709551603
Run Code Online (Sandbox Code Playgroud)
这显然不是我想要的。每当我尝试将 string::size() 乘以负数(但不是正数!)时,都会发生这个恼人的错误。我不明白这里出了什么问题。
在 中(-1)*a.size(),(-1)具有类型int并且a.size()具有无符号类型(可能size_t)。
(-1)*a.size()被计算为无符号整数,因为当二元运算应用于有符号类型和无符号类型时,提升和转换规则有利于无符号类型。