【问题标题】:How could a variable with a type of string::size_t be initialized to zerostring::size_t 类型的变量如何初始化为零
【发布时间】:2016-01-06 00:57:41
【问题描述】:
string s("Hello World!!!");// punct_cnt has the same type that s.size returns;  <br>
decltype(s.size()) punct_cnt = 0;// count the number of punctuation characters in s  <br>for (auto c : s) // for every char in s
if (ispunct(c)) // if the character is punctuation  <br>
++punct_cnt; // increment the punctuation counter  <br>
cout << punct_cnt<< " punctuation characters in " << s << endl;

这是 C++ Primer 5th 上的代码示例。
有人可以向我解释一下为什么它可以分配 0 来初始化一个不是整数类型的 string::size_t 类型的变量吗?
我在问答中找不到类似的问题。谢谢!

【问题讨论】:

  • 谁告诉你std::string::size_type不是整数类型?
  • @ForEveR 我想我见过类似 string::size_type is not int 因为 int 只能容纳 32 位但 string::size_t 可以保证容纳足够的数字。
  • @Des1gnWizard “不是int”和不是整数类型之间有很大的区别。 byteshortintlonglong long 都是整数/整数类型,但其中只有一个是 intint 的大小也不是一成不变的,see the table on this page,位宽:至少 16
  • @ForEveR 哦,,,是的,我实际上想说不是“int”,但无论如何都是错误的。感谢您指出这一点!

标签: c++ string size


【解决方案1】:

【讨论】:

    【解决方案2】:

    decltype(s.size())
    返回一个类型,在本例中为 size_t (unsigned int)。
    见:http://www.cplusplus.com/reference/cstring/size_t/

    【讨论】:

    • 哦..谢谢指出..我学C++好几天了,可能混淆了一些概念
    猜你喜欢
    • 2018-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-13
    • 2010-12-26
    相关资源
    最近更新 更多