问题描述
const std::string::size_type cols = greeting.size() + pad * 2 + 2;
为什么 string :: size_type
? int
应该工作!它拥有数字!!!
Why string::size_type
? int
is supposed to work! it holds numbers!!!
推荐答案
正如一个有符号的字符。
A short holds numbers too. As does a signed char.
但是这些类型都不能保证足够大以表示任何字符串的大小。
But none of those types are guaranteed to be large enough to represent the sizes of any strings.
string :: size_type
可以保证。
为了一个简单的例子,为什么这是必要的,考虑一下64位平台。一个int通常仍然是32位的,但你有远远超过2 ^ 32字节的内存。
For a simple example of why this is necessary, consider 64-bit platforms. An int is typically still 32 bit on those, but you have far more than 2^32 bytes of memory.
所以如果使用一个(signed)int, d无法创建大于2 ^ 31个字符的字符串。
size_type在这些平台上将是一个64位的值,所以它可以表示更大的字符串,没有问题。
So if a (signed) int was used, you'd be unable to create strings larger than 2^31 characters.size_type will be a 64-bit value on those platforms however, so it can represent larger strings without a problem.
这篇关于string :: size_type而不是int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!