【问题标题】:Creating an array of structs in C++在 C++ 中创建一个结构数组
【发布时间】:2011-11-06 13:00:30
【问题描述】:

我正在处理一项要求我使用“结构数组”的任务。我之前为这位教授的另一项任务做过一次,使用以下代码:

struct monthlyData {
    float rainfall;
    float highTemp; 
    float lowTemp;  
    float avgTemp;  
} month[12];

这很好地完成了工作,但我得到了标记为全局数组的点。我应该怎么做才能避免这种情况?整个夏天我都没有接触过 C++,所以我现在对它很生疏,不知道从哪里开始。

【问题讨论】:

  • 你不知道除了全局变量之外的任何其他类型的变量吗?

标签: c++ arrays struct


【解决方案1】:

简单地定义结构为:

struct monthlyData {
    float rainfall;
    float highTemp; 
    float lowTemp;  
    float avgTemp;  
};

然后在你需要的函数中创建这个结构的数组:

void f() {
    monthlyData month[12];
    //use month
}

现在数组不是全局变量。它是一个局部变量,您必须将此变量传递给其他函数,以便其他函数可以使用 same 数组。以下是您应该如何通过它:

void otherFunction(monthlyData *month) {
    // process month
}

void f() {
    monthlyData month[12];
    // use month
    otherFunction(month);
}

注意otherFunction 假定数组的大小是12(一个常数值)。如果大小可以是任何值,那么您可以这样做:

void otherFunction(monthlyData *month, int size) {
    // process month
}

void f() {
    monthlyData month[12];
    // use month
    otherFunction(month, 12); //pass 12 as size
}

【讨论】:

    【解决方案2】:

    好吧,你可以只在需要它的方法中声明数组:)

    struct monthlyData
    {
      float rainfall;
      float highTemp; 
      float lowTemp;  
      float avgTemp;  
    };
    
    int main()
    {
    
      monthlyData month[12];
    
    }
    

    如果您还需要从其他方法中使用它,请将其作为方法参数传递。

    【讨论】:

      【解决方案3】:

      先声明结构

      struct monthlyData { 
         float rainfall; 
         float highTemp;  
         float lowTemp;   
         float avgTemp;   
      };
      

      然后使用例如

      void foo()
      {
         struct monthlyData months[12];
         ....
      
      }
      

      【讨论】:

        猜你喜欢
        • 2012-05-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多