[英]Converting std::string::length to int
string::length has the return type of size_t, but it seems to able to be put into an int without any casting or anything. string :: length的返回类型为size_t,但似乎可以将其放入int中,而无需进行任何强制类型转换。 Why can I assign a size_t to an int in this case?
在这种情况下,为什么要为int分配一个size_t?
int main() {
string line;
getline(cin, line);
cout << line << endl;
int i = line.size();
int j = line.length();
cout << i << " " << j << endl;
}
The size_t
values are being narrowed. size_t
值正在缩小。 In c++11, you could make this fail with an error by doing: 在c ++ 11中,您可以通过执行以下操作使此失败并出现错误:
#include <string>
int main() {
std::string line;
int i{line.size()};
int j{line.length()};
}
The errors produced look like: 产生的错误如下所示:
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>( )
size_t is a 32 bit integer. size_t是32位整数。 Go to your compiler directory and open the stdio.h file.
转到编译器目录并打开stdio.h文件。
There is a declaration, something like this: 有一个声明,像这样:
typedef unsigned int size_t;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.