c++ - 初始化结构数组 C++ 时出现问题

标签 c++ arrays structure

我是 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/

相关文章:

matlab - 在Matlab中,如何对嵌套结构进行排序?

c - 将字符数组分配给结构体中的字符数组

c++ - 如何从基类调用后代函数?

javascript - 过滤不包含来自其他数组的字符串的字符串?

javascript - 检查 javascript 和 angularjs 中有多少个数组的长度大于 0

ruby - 在 Ruby 中的不同数组的特定位置从单个字符创建数组

c - 使用结构时 C 中的不完整类型错误

c++ - StartService FAILED 577自签名内核驱动程序,如何解决?

c++ - 使用带有 LibCurl 的代理服务器,它可以读取默认的 I.E.设置

c++ - OpenGL/Carbon/Cocoa 内存管理自动释放问题