使用结构变量作为形式参数

Using a struct variable as a formal parameter

#include <iostream>
using namespace std;

void input(partsType inventory[100]&)
{}

int main()
{
   struct partsType
   {

      string partName;
      int partNum;
      double price;
      int quantitiesInStock;
   };
   partsType inventory[100];
}

我正在尝试使用结构变量作为形式参数。稍后我将通过引用传递变量。

目前,我遇到错误

declaration is incompatible, and `partsType` is undefined. 

您有两个问题:

  • 您需要在 main 之外定义 partsType,当然 否则在 input 函数之前,它不知道什么是 partsType.
  • 其次,您的函数参数语法错误。它应该有 是
    void input(partsType (&inventory)[100])
    //                   ^^^^^^^^^^^^^^^^^^  --> if you meant to pass the array by ref
    

所以你需要:

#include <iostream>
#include <string>   // missing header

struct partsType
{
   std::string partName;
   int partNum;
   double price;
   int quantitiesInStock;
};

void input(partsType (&inventory)[100]) 
{}

int main()
{
   partsType inventory[100];
}

另一种选择是在 input 函数之前转发声明结构 partsType。但是,这将需要在 main 之后进行函数定义,因为您在 main:

中定义结构
#include <iostream>
#include <string>   // missing header

// forward declaration
struct partsType;
void input(partsType(&inventory)[100]);

int main()
{
   struct partsType
   {
      std::string partName;
      int partNum;
      double price;
      int quantitiesInStock;
   };
   partsType inventory[100];
}
void input(partsType(&inventory)[100])
{
   // define
}

也不用using namespace std;

练习