【问题标题】:Build error E0530 initialization with '{..}' expected for aggregate object构建错误 E0530 初始化,聚合对象应使用“{..}”
【发布时间】:2018-04-30 16:09:37
【问题描述】:

我正在尝试在这里创建一个大小为“i”的数组,其中 i 是先前定义的,(底部有完整代码)

double studentScores[] = new double[i];

但是我不断收到以下错误:

需要使用“{...}”进行初始化。

我已经尝试过指针方法,但它似乎不适用于我的其余代码。任何帮助将不胜感激,感谢您的宝贵时间。

int main()
{
    ifstream inData;                //input file stream variable
    ofstream outData;           //output file stream variable

    inData.open("Data.txt");        //open data file
    outData.open("testStatistics.out");

    int i = 0;
    while (inData.eof() == false)   //while you have not reached the end of the file
    {
        i++;                            //i == size of the class
    }
    double studentScores[] = new double[i];     //creates an array of the size of the number of inputs

    for (int j = 0; j < i; j++)
    {
        inData >> studentScores[j]; //read in student scores
    }

    double average1 = average(i, studentScores);
    double median1 = median(i, studentScores);

    int distribution[10] = { 0 };
    for (int v = 0; v < i; v++)         //increment distribution appropriately
    {
        int h = scoresDistribution(v, studentScores);
        distribution[h] ++;
    }

    outData << "There are " << i << "scores available." << endl;
    outData << "The average is : " << average1 << endl;
    outData << "The median is : " << median1 << endl;
    outData << "The detailed grade distribution is as follows : " << endl;

    outData << fixed << left;
    outData << setfill(' ') << setw(10) << "range" << setw(10) << " # of Students" << endl;
    int z = 100;
    int y = 90;
    for (int f = 0; f < 10; f++)
    {
        outData << setfill(' ');
        outData << setw(10) << "[" << z << " - " << y << "]";
        outData << distribution[f] << endl;
        z = z - 10;
        y = y - 10;
    }

    inData.close(); //close input data file
    outData.close(); //close output data file

    cout << "Press any key to quit…" << endl;

    cin.ignore(50, '\n');
    return 0;
}

【问题讨论】:

标签: c++ arrays compiler-errors initialization


【解决方案1】:
double studentScores[] = new double[i];

这是无效的C++。这看起来像一个残忍的C++/Java 混合体。

您不能在此处在堆栈上创建数组,因为这样做需要在编译时已知的固定大小。

现代C++最好的方法是使用std::vector

std::vector<double> studentScores;
studentScores.resize(i);

如果必须使用new,则必须使用指针,因为这是new 返回的:

double* studentScores = new double[i];

请注意,您必须在使用完毕后自行释放该内存:

delete[] studentScores;

在任何一种情况下,如果“这似乎不适用于我的其余代码”,您需要修复其余代码。您可能想为此提出一个单独的问题,或使用搜索来查找可以帮助您的问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-10-15
    • 1970-01-01
    • 1970-01-01
    • 2016-06-23
    • 2019-10-15
    • 2010-12-04
    • 2020-02-03
    • 2019-07-30
    相关资源
    最近更新 更多