【问题标题】:Using a struct variable as a formal parameter使用结构变量作为形式参数
【发布时间】:2020-07-29 16:15:44
【问题描述】:
#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. 

【问题讨论】:

  • input之前定义partsType

标签: c++ function struct parameters declaration


【解决方案1】:

你有两个问题:

  • 您需要在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;练习

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-04
    • 1970-01-01
    • 2018-09-01
    • 2020-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多