2

我正在做一些编程作业,我正在尝试使用 afor-loop来促进编码过程。这是循环:

#ifndef DIVSALES_H
#define DIVSALES_H

class DivSales
{
    public:
        DivSales(){ quarterSales[4] = {0}; };
        double getTotalSales() { return totalSales;}
        static void setTotalSales(double);
        static void addTotalSales(double);
        double getQuarterSales(int numQuarter) {return quarterSales[numQuarter];}
        void setQuarterSales(int numQuarter, double numAmount) { quarterSales[numQuarter] = numAmount;}
    private:
        static double totalSales;
        double quarterSales[];
};

double DivSales::totalSales = 0;
void DivSales::setTotalSales(double totalAmount) {totalSales = totalAmount; }
void DivSales::addTotalSales(double addAmount) {totalSales += addAmount; }
#endif // DIVSALES_H

#include <iostream>
#include "DivSales.h"

using namespace std;

int main()
{
    const int NUMDIVS = 6;
    const int NUMQUARTERS = 4;
    double amount = 0;

    DivSales divs[NUMDIVS];

    for(int division = 0; division < NUMDIVS; division++)
    {
        cout << "Division " << (division + 1) << endl;

        for(int quarter = 0; quarter < NUMQUARTERS; quarter++)
        {
            cout << "Quarter " << (quarter + 1) << ": ";
            cin >> amount;

            divs[division].setQuarterSales(quarter, amount);
            DivSales::addTotalSales(amount);
        }
    }


    return 0;
}

输出示例:

Division 1
Quarter 1: 500
Quarter 2: 500
Quarter 3: 500
Quarter 2: 500
Quarter 3: 500
Quarter 2: 500
Quarter 3: 500
Quarter 2: 500
Quarter 3: 500
Quarter 2: 

我想要做的是,当我输入一个分区的 4 个季度的数字时,它会移动到下一个分区。但是,在 4 个输入之后,它不会增加除法变量,for-loop而是继续要求更多输入。到底是怎么回事?

4

2 回答 2

2

我找到了导致该问题的原因,它位于 DivSales.h 文件中:

更改此行:

double quarterSales[];

对于这一行:

double quarterSales[4];

问题是您没有为 4 个元素的数组分配内存。要初始化它,请将您的构造函数更改为:

DivSales():quarterSales({0}){ };

您还应该将以下行移至 DivSales.cpp,否则我会收到多重定义错误:

double DivSales::totalSales = 0;
于 2013-10-25T15:44:36.177 回答
0

这里:

divs[division].setTotalSales(amount);

你可能想要:

divs[division].addTotalSales(amount);

但这不是导致您的问题的原因。我无法重现。

于 2013-10-25T15:35:38.397 回答