将std :: string :: length转换为int

时间:2014-10-18 16:03:11

标签: c++

string :: length的返回类型为size_t,但似乎可以放入int而不进行任何转换或任何操作。在这种情况下,为什么我可以将size_t分配给int?

int main() {
     string line;
     getline(cin, line);
     cout << line << endl;
     int i = line.size();
     int j = line.length();
     cout << i << " " << j << endl;
}

2 个答案:

答案 0 :(得分:3)

size_t值正在缩小。在c ++ 11中,您可以通过执行以下操作使其失败并显示错误:

#include <string>

int main() {
    std::string line;
    int i{line.size()};
    int j{line.length()};
}

产生的错误如下:

gh.cc:5:11: error: non-constant-expression cannot be narrowed from type 'size_type' (aka 'unsigned long') to 'int' in initializer list [-Wc++11-narrowing]
    int i{line.size()};
          ^~~~~~~~~~~
gh.cc:5:11: note: override this message by inserting an explicit cast
    int i{line.size()};
          ^~~~~~~~~~~
          static_cast<int>( )
gh.cc:6:11: error: non-constant-expression cannot be narrowed from type 'size_type' (aka 'unsigned long') to 'int' in initializer list [-Wc++11-narrowing]
    int j{line.length()};
          ^~~~~~~~~~~~~
gh.cc:6:11: note: override this message by inserting an explicit cast
    int j{line.length()};
          ^~~~~~~~~~~~~
          static_cast<int>( )

答案 1 :(得分:0)

size_t是32位整数。 转到编译器目录并打开 stdio.h 文件。

有一个声明,如下:

typedef unsigned int size_t;