派生对象的对象数组

时间:2012-07-06 23:25:31

标签: c++ inheritance

我有一个对象数组,它们都来自BaseStudent类。

BaseStudent**studentlist = new BaseStudent*[atoi(listSize.c_str())];

该数组使用派生的Math,English或History对象填充。我现在正在尝试从阵列中的每个对象打印出特定数据并将其输出到文件中。

for (int j=0; j<atoi(listSize.c_str()); j++){
    if(studentlist[j]->getMT() == ENGLISH){
        output << studentlist[j]->GetFN()<<" "<<studentlist[j]->GetLN();
        output << right << setw(42) << studentlist[j]->GetFinal(); // this is an English public function but I can't call this.
    }
}

我需要能够从对象数组中访问派生类私有成员数据。

这是我的标题。正如您所看到的,我为每个受保护的成员数据都设置了一个setter和getter。

#include <iostream>
#include <string>

using namespace std;

#ifndef BASESTUDENT_H
#define BASESTUDENT_H

enum MajorType {ENGLISH, HISTORY, MATH};
// *********************************************************************
// Base class. All other classes (Enlish, History, Math) inherit from 
// this class.
// *********************************************************************
class BaseStudent
{
public: 
    BaseStudent();
    BaseStudent(string fn, string ln, string m);
    string GetFN(){return firstName;}
    string GetLN(){return lastName;}
    MajorType getMT(){return course;}
    void SetFN(string fn){firstName = fn;}
    void SetLN(string ln){lastName = ln;}
    void SetMT(string m);

protected:
    string firstName;
    string lastName;
    MajorType course;

}; // End Base class

// *********************************************************************
// Enlish class.
// *********************************************************************

class English: public BaseStudent
{
public:
    English(string fn, string ln, string m, double a, double p, double mt, double f);
    double FinalAverage();
    double GetAttendance(){return attendance;}
    double GetProject(){return project;}
    double GetMidterm(){return midterm;}
    double GetFinal(){return final;}
    double GetFinalAverage(){return finalAverage;}
    void SetAttendance(double a){attendance = a;}
    void SetProject(double p){project = p;}
    void SetMidterm(double m){midterm = m;}
    void SetFinal(double f){final = f;}
    void SetFinalAverage(double fa){finalAverage = fa;}

protected: 
    double attendance;
    double project;
    double midterm;
    double final;
    double finalAverage;

}; // End English class

// *********************************************************************
// History class.
// *********************************************************************

class History: public BaseStudent 
{
public:
    History(string fn, string ln, string m, double t, double mt, double f);
    double FinalAverage();
    double GetTermPaper(){return termPaper;}
    double GetMidterm(){return midterm;}
    double GetFinalExam(){return finalExam;}
    double GetFinalAverage(){return finalAverage;}
    double FinalExam(){return finalExam;}
    void SetTermPaper(double t){termPaper = t;}
    void SetMidterm(double m){midterm = m;}
    void SetFinalExam(double f){finalExam = f;} 
    void SetFinalAverage(double fa){finalAverage = fa;}

protected:
    double termPaper;
    double midterm;
    double finalExam;
    double finalAverage;


}; // End History class.

// *********************************************************************
// Math class.
// *********************************************************************

class Math: public BaseStudent
{
public:
    Math(string fn, string ln, string m, double q1, double q2, double q3,
        double q4, double q, double t1, double t2, double f);
    double FinalAverage();
    double GetQuiz1(){return quiz1;}
    double GetQuiz2(){return quiz2;}
    double GetQuiz3(){return quiz3;}
    double GetQuiz4(){return quiz4;}
    double GetQuiz5(){return quiz5;}
    double GetFinalExam(){return finalExam;}
    double GetTest1(){return test1;}
    double GetTest2(){return test2;}
    double GetQuizAverage(){return quizAverage;}
    double GetFinalAverage(){return finalAverage;}
    void SetQuiz1(double q){quiz1 = q;}
    void SetQuiz2(double q){quiz2 = q;}
    void SetQuiz3(double q){quiz3 = q;}
    void SetQuiz4(double q){quiz4 = q;}
    void SetQuiz5(double q){quiz5 = q;}
    void SetTest1(double q){test1 = q;}
    void SetTest2(double q){test2 = q;}
    void SetFinalExam(double q){finalExam = q;}
    void SetQuizAverage();
    void SetFinalAverage(double fa){finalAverage = fa;}

protected:
    double quiz1;
    double quiz2;
    double quiz3;
    double quiz4;
    double quiz5;
    double test1;
    double test2;
    double finalExam;
    double quizAverage;
    double finalAverage;

}; // End Math class.

#endif

我是否需要某种虚拟功能的实现?

到目前为止,这是我的驱动程序:

#include<iostream>
#include<fstream>
#include<string>
#include<iomanip>
#include"basestudent.h"

using namespace std;

int main(void)
{
    string listSize;

    string fileIn = "";
    string fileOut = "";
    string firstname ="";
    string lastname ="";
    string major = "";
    string eolDummy;
    int mQuiz1, mQuiz2, mQuiz3, mQuiz4, mQuiz5, mTest1, mTest2, mFinalExam;
    int eAttendance, eProject, eMidterm, eFinalExam;
    int hTermPaper, hMidterm, hFinalExam;

    ifstream input;
    ofstream output;
    do{
        input.clear();

        cout << "Please enter the filename: ";
        cin >> fileIn;
        cout << "Please enter an output name: ";
        cin >> fileOut;

        input.open(fileIn);
        if (!input)
            cout << "Invalid file, please enter again." << endl;
    } while(!input);

    input >> listSize;
    BaseStudent**studentlist = new BaseStudent*[atoi(listSize.c_str())];
    int i = 0;
    while (!input.eof())
    {
        getline(input, lastname, ',');
        getline(input, firstname, '\n');

        input >> major;

        if (major == "Math") {
            input >>mQuiz1>>mQuiz2>>mQuiz3>>mQuiz4>>mQuiz5>>mTest1>>mTest2
                  >>mFinalExam>>eolDummy;
            // Math Constructor call
            // Array += object
            studentlist[i] = new Math(firstname,lastname,major,mQuiz1,mQuiz2,mQuiz3,mQuiz4,mQuiz5,
                                      mTest1,mTest2,mFinalExam);
        }
        else if (major == "History"){
            input >>hTermPaper>>hMidterm>>hFinalExam>>eolDummy;
            // History Constructor call
            // Array += object
            studentlist[i] = new History(firstname,lastname,major,hTermPaper,hMidterm,hFinalExam);
        }
        else if(major == "English"){
            input >>eAttendance>>eProject>>eMidterm>>eFinalExam>>eolDummy;
            // English Constructor call
            // Array += object
            studentlist[i] = new English(firstname,lastname,major,eAttendance,eProject,eMidterm,eFinalExam);
        }
        i++;
    }

    output.open(fileOut);
    output << "Student Grade Summary" << endl;
    output << "---------------------" << endl << endl;
    output << "ENGLISH CLASS "<<endl<<endl;
    output << "Student                                   Final   Final   Letter"<<endl;
    output << "Name                                      Exam    Avg     Grade"<<endl;
    output << "----------------------------------------------------------------"<<endl;
    for (int j=0; j<atoi(listSize.c_str()); j++){
        if(studentlist[j]->getMT() == ENGLISH){
            output << studentlist[j]->GetFN()<<" "<<studentlist[j]->GetLN();

            output << right << setw(42) << studentlist[j]->



    input.close();
    output.close();
    return 0;
}

1 个答案:

答案 0 :(得分:0)

当您从数组中获取指针时,需要使用dynamic_cast将其强制转换为相应的类

e.g。

BaseStudent *p = somearray[0];

if ( English* pEnglish = dynamic_cast<English*>(p) )
{
   // call the methods
   cout << p->FinalAverage();
   ...
}
else if ( History* pHistory = dynamic_cast<History*>(p) )
{
   // call the methods
}
else if ( Math* pMath = dynamic_cast<Math*>(p) )
{
   // call the methods
}

顺便说一下,使用矢量而不是原始数组,它更方便,更安全。

std::vector<BaseStudent*> yourvector;