c++ - 下面的代码报出bad allocation错误,求教为什么?
怪我咯
怪我咯 2017-04-17 10:59:13
0
1
571

下面的代码报出bad allocation错误,求教为什么?

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

class Student
{
public:
    Student();
    Student(int,string,float);//构造函数不能声明为虚函数,,,一般析构函数都声明都虚函数
    //在声明构造函数时,在最左边加virtual,声明为虚函数,用同一种方式调用同一类族中不同类的所有的同名函数。当基类的一个成员函数声明为虚函数时,默认其派生类中的同名函数自动成为虚函数
    virtual void display();
protected:
    int num;
    string name;
    float score;
};

Student::Student():num(0),name("NULL"),score(0){}
Student::Student(int n,string nam,float sco):num(n),name(nam),score(sco){
    cout<<"this is Student constructor."<<endl;
}
void Student::display()//在类外定义该函数时不必在加virtual
{   
    cout<<"student"<<endl;
    cout<<"num:"<<num<<endl;
    cout<<"name:"<<name<<endl;
    cout<<"score:"<<score<<endl;
}

class Graduate:public Student//注意此处为:而不是::
{
public:
    Graduate();
    Graduate(int,string,float,float);
    void display();
protected:
    float pay;
};

Graduate::Graduate():Student(),pay(0){}
Graduate::Graduate(int n,string nam,float sco,float p):Student(n,nam,sco),pay(p){
    cout<<"this is Graduate constructor."<<endl;
}
void Graduate::display()
{   
    cout<<"graduate"<<endl;
    cout<<"num:"<<num<<endl;
    cout<<"name:"<<name<<endl;
    cout<<"score:"<<score<<endl;
    cout<<"pay:"<<pay<<endl;
}


class Doctor:public Graduate
{
public:
    Doctor();
    Doctor(int,string,float,float,int);
    void display();
private:
    int age;
};

Doctor::Doctor():Graduate(),age(0){}
Doctor::Doctor(int n,string nam,float sco,float p,int a):Graduate(n,name,sco,p),age(a){
    cout<<"this is Doctor constructor."<<endl;
}


void Doctor::display()
{
    cout<<"Doctor"<<endl;
    cout<<"num:"<<num<<endl;
    cout<<"name:"<<name<<endl;
    cout<<"score:"<<score<<endl;
    cout<<"pay:"<<pay<<endl;
    cout<<"age"<<age<<endl;
}

void main()
{
    Student stud1(1,"haha",89.0);
    Graduate grad1(2,"fang",98.0,2000);
    Student *pt=&stud1;
    pt->display();
    pt=&grad1;
    pt->display();
    grad1.display();

    try{
        Doctor doc1(3,"lili",97.3,2090,20);//此处报错!!
        pt=&doc1;
        pt->display();
        doc1.display();
    }catch(std::exception const &ex)
    {
        cout<<ex.what()<<endl;
    }
}
怪我咯
怪我咯

走同样的路,发现不同的人生

Antworte allen(1)
迷茫

下次能仔细点嘛!

Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage