Using inheritance and dynamic binding

這是Acceleraated C++一書中第13章的代碼,中心思想是使用繼承和動態綁定來優化代碼,在實現該代碼的時候,學習了很多東西。附在代碼旁:

 

#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
#include<iomanip> //這是對控制precesion精度的,控制輸出流的格式
#include<stdexcept> //異常處理,像domain_error runtime_error都包含在該頭文件中
using namespace std;

 

//輸出平均分

double grade(double midterm, double final,const vector<double>& homework)
{
    double aver;
    for(int i=0;i<homework.size();i++)
        aver+=homework[i];
    aver/=homework.size();
    return 0.2*midterm+0.4*final+0.4*aver;
}

 

//讀入平常的作業分數,以0結束

istream& read_hw(istream& in, vector<double>& hw)
{
    if(in)
    {
        hw.clear();
       
        double temp;
        while(in>>temp,temp)
            hw.push_back(temp);
        in.clear();
    }

    return in;
}

//基本的分數

class Core
{
    friend class Student_info;  //Student_info是將Core及Grad包裹起來,允許Student_info訪問Core的私有成員
    public:       
        //constructor
        Core():midterm(0),final(0){}  //構造函數
        Core(istream& is){ read(is); }  //從輸入流中讀入成績
        virtual ~Core(){}  //虛構函數,設定爲虛擬的,但繼承Core的類不需要再設爲虛擬的了,如果繼承Core的類不需要在析構函數中定義特別的代碼,那它(繼承Core的類)也不必去定義虛構函數

        string name() const;
        virtual double grade() const; //const的定義代表其不改變任何數據,virtual代表其版本可由繼承類重載,繼承類的版本不需要加virtual關鍵字了
        virtual istream& read(istream&);

    protected:
        istream& read_common(istream&);
        double midterm, final;
        vector<double> homework;
        virtual Core* clone() const { return new Core(*this); }  //這個就是深度複製了,重新申請內存,注意,this是一個指針,指向自己

    private:
        string n; //代表學生的序號
};

string Core::name() const
{
    return n;
}

double Core::grade() const
{
    return ::grade(midterm,final,homework);
}

istream& Core::read_common(istream& in)
{
    in>>n>>midterm>>final;
    return in;
}

istream& Core::read(istream& in)
{
    read_common(in);  //先讀入學生序號,期中成績,期末成績
    read_hw(in,homework);  //讀入平時的作業成績
    return in;
}

 

//繼承自Core

class Grad:public Core
{
    public:
        Grad():thesis(0){}
        Grad(istream& is){ read(is); }
        double grade() const;
        istream& read(istream&);

    private:
        double thesis;
    protected:
        Grad* clone() const { return new Grad(*this); }
};

istream& Grad::read(istream& in)
{
    read_common(in);
    in>>thesis;
    read_hw(in,homework);
    return in;
}

double Grad::grade() const
{
    return min(Core::grade(),thesis);
}

 

//包含一個Core基類指針的類,它維護Core指針

class Student_info
{
    public:
        Student_info():cp(0){} //默認構造函數
        Student_info(istream& is):cp(0){ read(is); } //從輸入流輸入,創建Student_info對象
        Student_info(const Student_info&); //複製構造函數,從一個Student_info複製到本Student_info對象中
        Student_info& operator=(const Student_info&); //賦值操作符函數
        ~Student_info(){ delete cp; }  //析構函數,將cp指向的內存釋放掉

        istream& read(istream&);
        string name() const
        {
            if(cp) return cp->name();  //調用前先考慮下cp是否指向一個真正的Student_info對象
            else throw std::runtime_error("uninitialized student");
        }

        double grade() const
        {
            if(cp) return cp->grade();
            else throw std::runtime_error("uninitialized student");
        }

        static bool compare(const Student_info& s1, const Student_info& s2)
        {
            return s1.name()<s2.name();
        }

    private:
        Core* cp;
};

Student_info::Student_info(const Student_info& s):cp(0)
{
    if(s.cp) cp=s.cp->clone();
}

Student_info& Student_info::operator=(const Student_info& s)
{
    if(&s!=this) //判斷別是自身複製了
    {
        delete cp;
        if(s.cp)
        {
            cp=s.cp->clone();
        }
        else
            cp=0;
    }
    return *this;
}

istream& Student_info::read(istream& is)
{
    delete cp;

    char ch;
    is>>ch;

    if(ch=='U')
        cp=new Core(is);
    else
        cp=new Grad(is);

    return is;
}

bool compare(const Core& c1,const Core& c2)
{
    return c1.name()<c2.name();
}

bool compare_grades(const Core& c1, const Core& c2)
{
    return c1.grade()<c2.grade();
}

bool compare_Core_ptrs(const Core* cp1, const Core* cp2)
{
    return compare(*cp1,*cp2);
}

 

//使用裝Core對象的vector來測試下

int Core_test()
{
    vector<Core> students;
    Core record;
    string::size_type maxlen=0;

    while(record.read(cin),record.name()!="0")
    {
        maxlen=max(maxlen,record.name().size());
        students.push_back(record);
    }

    sort(students.begin(),students.end(),compare);

    for(vector<Core>::size_type i=0; i!=students.size(); ++i)
    {
        cout<<students[i].name()
            <<string(maxlen+1-students[i].name().size(),' ');
        try
        {
            double final_grade=students[i].grade();
            streamsize prec=cout.precision();
            cout<<setprecision(3)<<final_grade<<setprecision(prec)<<endl;
        }
        catch(exception e )
        {
            cout<<e.what()<<endl;
        }
    }
    return 0;
}

 

//使用裝Grad對象的vector來測試下

int Grad_test()
{
    vector<Grad> students;
    Grad record;
    string::size_type maxlen=0;

    while(record.read(cin),record.name()!="0")
    {
        maxlen=max(maxlen,record.name().size());
        students.push_back(record);
    }

    sort(students.begin(),students.end(),compare);

    for(vector<Grad>::size_type i=0; i!=students.size();++i)
    {
        cout<<students[i].name()<<string(maxlen+1-students[i].name().size(),' ');
        try
        {
            double final_grade = students[i].grade();
            streamsize prec = cout.precision();
            cout<<setprecision(3)<<final_grade<<setprecision(prec)<<endl;
        }catch(exception e)
        {
            cout<<e.what()<<endl;
        }
    }
    return 0;
}

 

//如果只是用放對象的Vector來測試的話,那我們要對Core和Grad類分別寫函數了,就像上面的一樣,而如果用指針或引用的話,就不一樣了,不需要再分別寫了,只寫一個函數就可以了

int Core_pointer_test()
{
    vector<Core*> students;
    Core* record;
    char ch;
    string::size_type maxlen=0;

    while(cin>>ch)
    {
        if(ch=='U')
            record=new Core;
        else
            record=new Grad;
        record->read(cin);
        if(record->name()=="0")
            break;
        maxlen=max(maxlen,record->name().size());
        students.push_back(record);
    }
   
    sort(students.begin(),students.end(),compare_Core_ptrs);

    for(vector<Core*>::size_type i=0; i!=students.size();++i)
    {
        cout<<students[i]->name()<<string(maxlen+1-students[i]->name().size(),' '); //這是爲了保證輸出整齊
        try
        {
            double final_grade=students[i]->grade();
            streamsize prec=cout.precision();
            cout<<setprecision(3)<<final_grade<<setprecision(prec)<<endl;
        }
        catch(exception e)
        {
            cout<<e.what()<<endl;
        }
        delete students[i]; //別忘記釋放內存了
    }
    return 0;
}

 

//用Handle比上面的用指針有一個顯著的好處,那就是不用手動的申請,手動的釋放內存了。因爲這些操作都已經託管到Handle類裏了。

int Handle_test()
{
    vector<Student_info> students;
    Student_info record;
    string::size_type maxlen=0;

    while(record.read(cin),record.name()!="0")
    {
        maxlen=max(maxlen,record.name().size());
        students.push_back(record);
    }

    sort(students.begin(),students.end(),Student_info::compare);

    for(vector<Student_info>::size_type i=0; i!=students.size();++i)
    {
        cout<<students[i].name()<<string(maxlen+1-students[i].name().size(),' ');
        try
        {
            double final_grade=students[i].grade();
            streamsize prec=cout.precision();
            cout<<setprecision(3)<<final_grade<<setprecision(prec)<<endl;
        }
        catch(domain_error e)
        {
            cout<<e.what()<<endl;
        }
    }
    return 0;
}

int main()
{
    Handle_test(); //還可以對上面的其它含test的函數進行測試,結果是一樣的
    return 0;
}

 

該程序實現的功能是:輸入多條學生的序號,期中考試成績,期末考試成績,平時作業成績數據,按照計算規則,輸出每個學生的平均分。程序使用了C++的繼承,多態,動態類別識別,三原則(複製構造函數,賦值操作符,析構函數)等特性。

發佈了46 篇原創文章 · 獲贊 79 · 訪問量 25萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章