为什么 str.length() 输出为字符?

Che*_*ang -2 c++ string char string-length

这是我的 C++ 代码:

#include<bits/stdc++.h>
using namespace std;
int main()
{
    string str1;
    cin>>str1;
    int j=-1;
    cout<<typeid(str1.length()).name()<<endl;
    cout<<(j>str1.length())<<endl;
    int len=str1.length();
    cout<<len<<' '<<(j>=len);
}
Run Code Online (Sandbox Code Playgroud)

我输入:

abc
Run Code Online (Sandbox Code Playgroud)

结果是:

j
1
3 0
Run Code Online (Sandbox Code Playgroud)

可以看出,typeid(str1.length()).name()j,并且-1>str1.length()

我想知道为什么会这样

eer*_*ika 5

我想知道为什么会这样

typeid(str1.length()).name() 是 j

因为这就是您的语言实现碰巧破坏类型名称的方式。在我的系统上它是 m。

需要明确的是,该类型与std::size_t无符号整数类型的别名相同。

和 -1>str1.length()

这是因为,作为负数,-1 在无符号类型的可表示值之外,当转换到可表示范围时,它变得大于 3。实际上,转换为无符号的 -1 将是最大可表示值那种类型。