动态分配/指针/类问题 - 任何建议?

时间:2017-05-13 03:44:09

标签: c++

我的代码中的所有内容对我都有意义,但由于某种原因它最终只会执行前两个cout然后退出程序,其中.getHi的值是第一个输入值,无论什么和.getLow做同样的事情事情。我不熟悉动态分配或指针,所以我认为它可能与此有关,但我无法弄清楚我的代码有什么问题。有什么建议吗?

编辑:当我使用.getI时,它显示正确的值,所以我认为它在类函数中的某个地方让我感到困扰。

#include <iostream>
#include <memory>

using namespace std;

void input();

class Scores
{
    public:
        // ConstructorS & destructor
        Scores()
        {
        }
        Scores(int size)
        {
            fPtr = new float[size];
        }
        ~Scores()
        {
            delete [] fPtr;
        }

        //Member functions
        void setI(int x, float y)
        {
            fPtr[x] = y;
        }
        float getI(int x)
        {
            return fPtr[x];
        }
        float getHi()
        {
            int max = fPtr[0];
            for (int i=0;i<size;i++)
            {
                if (fPtr[i] > max)
                {
                    max = fPtr[i];
                }
            }
            return max;
        }
        float getLow()
        {
            int min = fPtr[0];
            for (int i=0;i<size;i++)
            {
                if (fPtr[i] < min)
                {
                    min = fPtr[i];
                }
            }
            return min;
        }
        float getAvg()
        {
            int total = 0;
            for (int i=0;i<size;i++)
            {
                total += fPtr[i];
            }
            return (total/size);
        }
    private:
        // Variables & pointers
        int size;
        float* fPtr;
};

int main()
{
    input();
}

void input()
{
    int nGroups = 0; 
    int nStudents = 0;
    float score;
    cout << "Enter the number of groups: ";
    cin >> nGroups; // Get number of groups
    Scores* arr;
    arr = new Scores[nGroups];
    for (int i=0;i<nGroups;i++) // Do once for each group...
    {
        cout << "Enter the number of students in group " << i+1 << ": "; // Ask for number of students in group
        cin >> nStudents; // Read in number of students
        arr[i] = Scores(nStudents); // Store a new Scores object at each element of an array
        for (int j=0;j<nStudents;j++)
        {
            cout << "Enter the score for student " << j+1 << ": ";
            cin >> score;
            arr[i].setI(j,score);
        }
        cout << "The highest score for group " << i+1 << " was " << arr[i].getHi() << "." << endl;
        cout << "The lowest score for group " << i+1 << " was " << arr[i].getLow() << "." << endl;
        cout << "The average score for group " << i+1 << " was " << arr[i].getAvg() << "." << endl;
    }
    delete [] arr;
}

1 个答案:

答案 0 :(得分:0)

检查Score(int)构造函数。您使用size参数但不初始化size成员,使其处于未初始化状态。

您的代码:

Scores(int size)
{
    fPtr = new float[size];
}

你需要这样做:

Scores(int size) : size(size)
{
    fPtr = new float[size];
}

在此之后,您可以在sizegetHigetLow内使用类变量getAvg