【问题标题】:Purpose of using (int) in the code below?在下面的代码中使用 (int) 的目的是什么?
【发布时间】:2020-06-27 06:03:14
【问题描述】:
n=b.size()    
n = max(n,(int)a.size());

其中 a 和 b 是一些用户输入字符串,n 是整数。谁能告诉我为什么我们使用 (int)a.size() 以及使用 (int) 的目的是什么。

【问题讨论】:

  • n的类型是什么?
  • n的类型是整数。
  • 如果你去掉强制转换,你可能会收到一个关于有符号/无符号不匹配的编译器警告,将 size_t 强制转换为 int 会使它消失。
  • std::max 是一个模板。看一下它的定义,您可能会弄清楚。 en.cppreference.com/w/cpp/algorithm/max

标签: c++


【解决方案1】:

我假设 n 的类型是int,你的程序会是这样的:

#include <iostream>
#include <string>

using namespace std;
int main ()
{
    string a ("Test string");
    string b ("Test two");

    int n = b.size()    ;
    n = max(n,(int)a.size());
    cout << "n : " << n ;

    return 0;
}

现在,如果您看到 string 类的 .size() 方法的 documentation,您将看到它返回的值类型为:size_t

size_t 是无符号整数类型(与成员类型相同 字符串::size_type) :根据documentation

现在,当我们查看documentation for max() 时,您可以看到它使用模板(您可以阅读更多关于模板化here 的内容)它的本质意味着您可以使用任何type 作为参数(int、float 等) ..) 但两个参数必须是同一类型。

现在由于n 在调用max(n,x); 时被声明为intx 需要是n 的类型,这在我们的例子中基本上意味着int

这就是在a.size() 之前使用(int) 的原因。我们在这里所做的是type casting,因为a.size() 返回的类型 size_tint 不同(您可以阅读有关此here 的更多信息),我们需要将返回值类型转换为 int,这可以通过 (int)a.size() 完成。

旁注

 int n = max(b.size(),a.size());
 cout << "n : " << n << " \n";

也可以,因为两者都是相同的类型,所以不需要进行类型转换。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-30
    • 2016-05-29
    • 2018-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多