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++的继承,多态,动态类别识别,三原则(复制构造函数,赋值操作符,析构函数)等特性。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值