C++ 在C++;
我正在做一项作业,要求我使用“结构数组”。我之前为这位教授的另一项作业做过一次,使用以下代码:C++ 在C++;,c++,arrays,struct,C++,Arrays,Struct,我正在做一项作业,要求我使用“结构数组”。我之前为这位教授的另一项作业做过一次,使用以下代码: struct monthlyData { float rainfall; float highTemp; float lowTemp; float avgTemp; } month[12]; 这使工作做得很好,但我得到了标记,因为数组是全局的。我应该做些什么来避免这种情况?整个夏天我都没有接触过C++,所以我现在对它很生疏,而且没有线索可以从这里开始。 <
struct monthlyData {
float rainfall;
float highTemp;
float lowTemp;
float avgTemp;
} month[12];
这使工作做得很好,但我得到了标记,因为数组是全局的。我应该做些什么来避免这种情况?整个夏天我都没有接触过C++,所以我现在对它很生疏,而且没有线索可以从这里开始。 < P>简单的将结构定义为:
struct monthlyData {
float rainfall;
float highTemp;
float lowTemp;
float avgTemp;
};
然后在函数中创建此结构的数组,您需要它:
void f() {
monthlyData month[12];
//use month
}
现在,数组不是全局变量。它是一个局部变量,您必须将此变量传递给其他函数,以便其他函数可以使用相同的数组。以下是你应该如何通过考试:
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
}
首先删除结构
struct monthlyData {
float rainfall;
float highTemp;
float lowTemp;
float avgTemp;
};
然后使用例如
void foo()
{
struct monthlyData months[12];
....
}
那么,只能在需要数组的方法中声明该数组:)
如果您还需要从另一个方法使用它,您可以将它作为方法参数传递。除了全局变量之外,您不知道其他类型的变量,所以您不知道这一点吗?
struct monthlyData
{
float rainfall;
float highTemp;
float lowTemp;
float avgTemp;
};
int main()
{
monthlyData month[12];
}