为什么在函数参数中指定数据类型但不指定struct? C ++

时间:2017-06-05 21:49:14

标签: c++ struct

根据我的理解,用C ++编写函数是这样的:

 int  foo(int x) 
    {
    //some code
    }

首先,int是数据类型,为什么我们需要指定它? 其次,如果我们有这样的代码:

  struct Monster
{
    std::string name;
    int health;

};
int printMonster(Monster myMonster)
    {

        std::cout << "This monster is named " << myMonster.name << " and has " << myMonster.health << " health" << std::endl;
        return 0;

为什么我们要编写结构名称,在这种情况下&#34; Monster&#34;而不是结构?

1 个答案:

答案 0 :(得分:0)

对于第一个问题

First of all, int is the data type, why do we need to specify it?

在C / C ++中,您必须指定变量的数据类型。但您也可以使用像M.M建议的auto关键字。你可以使用它,但我不建议像这样使用它。

关于第二个问题

Why do we write the struct name, in this case "Monster" instead of struct?

这样想。使用关键字structclass时,您将创建自己的数据类型。 Monster是您创建的数据类型。由于C ++需要所有变量的数据类型,因此您将数据类型编写为Monster

相关问题