我是 C++ 新手,正在研究一个类问题:
4. Annual Rainfall Report
Write a program that displays the name of each month in a year and its rainfall amount, sorted in order of rainfall from highest to lowest. The program should use an array of structures, where each structure holds the name of a month and its rainfall amount. Use a constructor to set the month names. Make the program modular by calling on different functions to input the rainfall amounts, to sort the data, and to display the data.
这是我到目前为止的代码:
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
struct Month //defining the structure
{
string name;
double rain;
Month(string name = "", double rain = 0){} //constructor
};
const int SIZE = 12; //12 months
//initializing each structure with the name
Month month[SIZE] = { Month("January", 0), Month("February",0), Month("March", 0),
Month("April", 0), Month("May", 0), Month("June", 0),
Month("July", 0), Month("August", 0), Month("September", 0),
Month("October", 0), Month("November", 0), Month("December",0)};
void rainIn();
void sort();
void display();
int main() {
rainIn();
display();
return 0;
}
void rainIn()
{
for (int i = 0; i < SIZE; ++i)
{
cout << "Please enter the rainfall for " << month[i].name << ": ";
cin >> month[i].rain;
}
}
void sort() //will write later
{ }
void display()
{
for (int i = 0; i < SIZE; ++i)
{
cout << month[i].name << month[i].rain << endl;
}
}
我遇到的问题是,当我尝试调用月份名称时,该月份的名称没有显示。我是否错误地初始化了数组?
阅读评论和答案后,我开发了一个“最小、完整、可验证”的示例:
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
struct Month
{
string name;
double rain;
Month(string n = "", double r = 0) {}
};
Month month("January", 12);
int main() {
cout << month.name << " had " << month.rain << " inches of rain. " << endl;
return 0;
}
这仍然给我带来了同样的问题。我更改了构造函数(并添加了成员初始化列表),如下所示:
Month(string n = "", double r = 0) : name{n}, rain{r} {}
并且成功了。
最佳答案
问题不在于数组,而在于构造函数实际上并未将成员变量设置为输入值。试试这个:
Month(string name = "", double rain = 0) : name{name}, rain{rain} {} //constructor
此语法称为“成员初始化列表”。如果你觉得它很陌生,请看看 this .
关于c++ - 初始化结构数组 C++ 时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33189649/