题目描述

定义一个学生基类Student,包括私有数据成员:学校名、姓名、年龄,输出数据成员值的公有成员函数Print()。再定义一个研究生类G_Student,公有继承方式派生于学生类Student,其中新增私有数据成员:导师姓名,并定义输出研究生数据的公有成员函数Print()。实现学生信息的输出。 键盘输入:MIT Kate 20 Smith 输出:MIT大学的Kate年龄20导师是Smith

输入

MIT Kate 20 Smith

输出

MIT大学的Kate年龄20导师是Smith

附ac代码

#include<iostream>
#include<cstring>
using namespace std;
class student {
protected:
    char* school;
    char* name;
    int old;
public:
    student(char* s, char* n, int o)
    {
        school = new char[strlen(s) + 1];
        if (school != 0) strcpy(school, s);
        name = new char[strlen(n) + 1];
        if (name != 0) strcpy(name, n);
        old = o;
    }
    void Print()
    {
        cout << school << "大学的" << name << "年龄" << old;
    }
    ~student()
    {
        delete[] school;
        delete[] name;
    }
};
class G_Student :public student {
private:
    char* teacher;
public:
    G_Student(char* s, char* n, int o, char* t):student(s, n, o)//此处括号里应为实参
    {
        teacher = new char[strlen(t) + 1];
        if (teacher != 0) strcpy(teacher, t);
    }
    void Print()
    {
        cout << school << "大学的" << name << "年龄" << old << "导师是" << teacher;
    }
    ~G_Student()
    {
        delete[] teacher;
        //不能去delete[] school;
    }

};
int main()
{
    char s[50]; char n[50]; int o; char t[50];
    cin >> s >> n >> o >> t;
    G_Student g(s, n, o, t);
    g.Print();
    return 0;
}

 

 posted on 2022-12-25 22:57  ruoye123456  阅读(40)  评论(0)    收藏  举报