繁体   English   中英

初始化结构数组的问题C ++

[英]Trouble Initializing an Array of Structures C++

我是C ++的新手,正在研究类问题:

4.年度降雨报告

编写一个程序,显示一年中每个月的名称及其降雨量,并按降雨量从高到低的顺序排序。 该程序应使用一系列结构,其中每个结构都包含一个月的名称及其降雨量。 使用构造函数设置月份名称。 通过调用不同的功能以输入降雨量,分类数据并显示数据,使程序模块化。

这是我到目前为止的代码:

#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

该语法称为“成员初始化列表” 如果它应该陌生的你,看看这个

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM