C ++类,基本重载错误

时间:2015-03-22 00:58:22

标签: c++ class

我正在尝试创建一个程序,使一个名为student的类成为学生ID,成绩数组,以及显示数组中有多少成绩的数字。该课程应该有成员方法输入学生ID号,输入单个考试成绩并更新输入的成绩总数,并计算平均成绩并显示学生ID,然后显示平均成绩。到目前为止,这是我的代码。

#include <iostream>

using namespace std;

class Student
{
public:
    int StudentID;
    double Grades[5];
    int NumberOfGrades;

    // Member functions declared here
    int setID(int id);
   double setGrades(double g[5]);
   double getAverage(void);
};

// make them functions work, son.


int Student::setID(int ID)
{
    cout << "Please enter in the student's ID number: ";
    cin >> ID;
    return 0;
}

double Student::setGrades(double g[5])
{
    for (int i = 0; i < 5; i++)
    {
        cout << "Please enter in grade number " << i ;
        cin >> g[i];
        NumberOfGrades++;
    }
    return 0;
}

double Student::getAverage(void)
{
    int sum = 0,average;  // declare what I need in average
    for (int i = 0; i < 5; i++)
    {
        sum = sum + Grades[i];
    }
    average = sum / NumberOfGrades;

    cout << "The average for " << StudentID << " is " << average;
    return 0;
}


int main ()
{
    Student Student1;

    Student1.setID; //  error
    Student1.setGrades; //  error
    Student1.getAverage();

}

我收到的错误是它无法解析重载函数的地址。有人可以用最简单的方式向我解释一下过载功能是什么吗?另外,如果可能,有人可以解释为什么我的代码中出现了错误吗?

2 个答案:

答案 0 :(得分:1)

首先,您需要实际调用这些功能:

Student1.setID -> Student1.setID()
Student1.setGrades -> Student1.setGrades()

这还不够,但这些函数需要参数(分别为int和double [5])。所以:

int id = 65;
double grades[5] = { 3.5, 4.0, 4.0, 3.0, 4.5 };

Student1.setID(id);
Student1.setGrades(grades);

但这只会删除编译器错误。也许您没有看到这一点,但您的功能实现不正确:

int Student::setID(int ID)
{
    cout << "Please enter in the student's ID number: ";
    cin >> ID; //you fill ID, which is a temporary variable!
    return 0;
}

另外,如果您要求setID()内的用户输入id,此参数的用途是什么?删除它 - 将setID(int ID)更改为setID()

int Student::setID()
{
    int input_id;
    cout << "Please enter in the student's ID number: ";
    cin >> input_id;
    this->StudentID = input_id;
    return 0;
}

答案 1 :(得分:0)

我发现代码存在一些主要问题:

int Student::setID(int ID)
{
    cout << "Please enter in the student's ID number: ";
    //ID is local. Assigning any value to it will have no effect on the class
    cin >> ID;
    //You might as well not return anything if the function is purely impure
    return 0;
}

另一个问题是“setter”不应该从用户那里获取输入并进行分配;这是两个单独的任务。我将此功能设置为:

void Student::setID(int ID)
{
    StudentID = ID;
}

请注意,我们将作为参数传入的值分配给StudentID。使用如下:

//In main
Student student;
int newStudentID = 1234;
student.setID(newStudentID);