Какие аргументы вы должны передать при перегрузке функции для класса - PullRequest
0 голосов
/ 14 октября 2018

Есть 2 прокомментированных раздела кода, где нам были даны следующие 2 назначения:

Добавьте сюда функцию перегрузки оператора для оператора <, чтобы позволить сравнение двух объектов NEPerson.Он вернет true, если имя первого человека в алфавитном порядке предшествует имени второго. </p>

Добавьте сюда функцию перегрузки оператора для оператора <, чтобы можно было сравнивать два объекта NEStudent.Он вернет истину, только если средний балл первого студента меньше среднего балла второго студента.</p>

Когда я компилирую код, я получаю СТЕНУ ошибок, так что я почти уверен, что просто не знаю, что я делаю, все это довольно ново для меня.Буду признателен за любую помощь.Если уже неясно, в чем мне в основном нужна помощь, так это перегрузка оператора "<".</p>

        #include <iostream>
        #include <string>
        using namespace std;

        class NEPerson {
        private:
                int id;
                string pname;
                string address;
        public:
                NEPerson(int d, string n, string a)
                { id = d;  pname = n; address = a;}
                virtual void printInfo() {
                   cout << "Name: " << pname;
                   cout << "\t ID: " << id;
                   cout << "\t Address: " << address << endl;
        }

        // Q1
        bool operator< (const NEPerson &p2) const
{
    return pname < p2.pname;
}

        };

        class NEStudent : public NEPerson {
        private:
                string major;
                float gpa;
                int CurCoursesNum;
                string* CurEnrolledCourses;
        public:
                NEStudent(int d, string n, string a, string m, float g, int cnum):NEPerson(d, n, a)
        { major = m; gpa = g; CurCoursesNum = cnum; }
                void addEnrolledCourses() {
                        CurEnrolledCourses = new string[CurCoursesNum];
                        cout << "Enter the code of " << CurCoursesNum;
                        cout << " course(s) for the student:\n";
                        for (int i = 0; i < CurCoursesNum; i++) cin >> CurEnrolledCourses[i];            }

                virtual void printInfo() {
                        NEPerson::printInfo();
                        cout << "\t Student Major: " << major;
                        cout << "\t GPA = " << gpa;
    cout << "\n\t Taking Courses:\n";
                    for (int i = 0; i < CurCoursesNum; i++)
                        cout << "\t   " << CurEnrolledCourses[i] << endl;
                     }
    // question 2 here asks the same as question 1 but for student.
   bool operator< (const NEStudent &s2) const
{
    return gpa < s2.gpa;
}

    ~NEStudent()
        { if (!CurEnrolledCourses) delete[] CurEnrolledCourses; }
    };


    class NETeacher : public NEPerson {
    private:
            string rank;
            string department;
            int CurCoursesLoad;
            string* CurCoursesTeaching;
    public:
            NETeacher(int d, string n, string a, string r, string p, int cnum) :NEPerson(d, n, a)
    { rank = r; department = p; CurCoursesLoad = cnum;}
            virtual void printInfo() {
             NEPerson::printInfo();
             cout << "\t Teacher Rank: " << rank;
             cout << "\t Department = " << department;
             cout << "\n\t Teaching Courses:\n";
             for (int i = 0; i < CurCoursesLoad; i++)
             cout << "\t   " << CurCoursesTeaching[i] << endl;
            }

            void addCoursesTeaching() {
                CurCoursesTeaching = new string[CurCoursesLoad];
                cout << "Enter the code of " << CurCoursesLoad;
                cout << " course(s) for the teacher:\n";
                        for (int i = 0; i < CurCoursesLoad; i++)
                             cin >> CurCoursesTeaching[i]; }
    ~NETeacher()
    { if (!CurCoursesTeaching) delete[] CurCoursesTeaching; }
    };
    //A template function that prints the info of two objects based on their < relation.
    template <class T>
    void PrintOrdered(T &v1, T &v2) {
            if (v1 < v2) { v1.printInfo(); v2.printInfo(); }
            else { v2.printInfo(); v1.printInfo(); }
    }

    int main() {
      NEStudent s1(111, "John", "Boston", "CE", 3.2, 2);
      NEStudent s2(222, "Emily", "Cambridge", "CS", 3.6, 3);
      NETeacher t1(888, "Adam", "Dedham", "Assistant Professor", "EECE", 3);
      NETeacher t2(999, "Mary", "Foxboro", "Associate Professor", "CS", 2);

      s1.addEnrolledCourses(); s2.addEnrolledCourses();

      t1.addCoursesTeaching(); t2.addCoursesTeaching();

      NEPerson* ps1 = &s1;
      NEPerson* ps2 = &s2;
      NEPerson* pt1 = &t1;
      NEPerson* pt2 = &t2;

      ps1‐>printInfo();
      ps2‐>printInfo();
      pt1‐>printInfo();
      pt2‐>printInfo();

      cout << "\n Students ordered by GPA (Ascending):\n";
      PrintOrdered(s1, s2);
      cout << "\n Teachers ordered alphabetically (Ascending):\n";
      PrintOrdered(t1, t2);
      cout << "\n Students ordered alphabetically:\n";

    //    PrintOrdered(???, ???);
    return 0;
    }

1 Ответ

0 голосов
/ 14 октября 2018

Это гораздо проще, чем вы думаете - просто сравните участников.
И не забудьте const.

bool operator< (const NEPerson &p2) const
{
    return pname < p2.pname;
}

(«pname» - странное имя. Почему не «name»«?)

...