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

标签 c++ function struct parameters declaration

#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. 

最佳答案

您有两个问题:

  • 您需要在partsType和类(class)之外定义main否则,在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];
    }
    

    另一种选择是在partsType函数之前预先声明struct input。但是,这需要在main之后进行函数定义,因为您在main中定义了struct:
    #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;

    关于c++ - 使用结构变量作为形式参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63157992/

    相关文章:

    c# - 模拟鼠标单击侧边按钮

    C++:直接使用派生类型的模板方法模式

    function - 有没有办法评估一个函数作为匹配臂的输入?

    c - 灵活数组成员(零长度数组)

    c# - 如何使用 Marshal.SizeOf 忽略结构中的字段大小?

    c++ - 运算符重载可以在没有引用的情况下工作吗?

    c++ - Windows 线程 : beginthread or QueueUserWorkItem (C++)

    使用函数进行 C 编程

    javascript - 自动绑定(bind)JS类方法有什么好方法?

    c - 一次调用多个函数的程序不断崩溃。 (C语言编程)