1、类定义如下:

// Person类
class Person{
protected:
    string name;
    int age;
public:
    Person(string n, int a): name(n), age(a){}
    virtual ~Person(){}
    virtual void display(){}
};

// Date类
class Date{
private:
    int year, month, day;
public:
    Date(int y, int m, int d): year(y), month(m), day(d){}
    void display(){ cout << year << '/' << month << '/' << day << endl; }
};

// Student类
class Student: public Person{
private:
    Date birthday;
    double score;
public:
    Student(string n, int a, Date b, double s): Person(n, a), birthday(b), score(s){}
    void setScore(double s){ score = s; }
    void display(){
        cout << "Name: " << name << endl;
        cout << "Age: " << age << endl;
        cout << "Birthday: ";
        birthday.display();
        cout << "Score: " << score << endl;
    }
};

// Teacher类
class Teacher: public Person{
private:
    string title;
public:
    Teacher(string n, int a, string t): Person(n, a), title(t){}
    void setScore(Student& s, double score){ s.setScore(score); }
    void display(){
        cout << "Name: " << name << endl;
        cout << "Age: " << age << endl;
        cout << "Title: " << title << endl;
    }
};

2、主函数如下:

int main(){
    // 输入学生的数据
    string name;
    int age, year, month, day;
    double score;
    cin >> name >> age >> year >> month >> day >> score;
    Date birthday(year, month, day);
    Student s(name, age, birthday, score);

    // 输入教师的数据
    string tname, title;
    int tage;
    cin >> tname >> tage >> title;
    Teacher t(tname, tage, title);

    // 输入学生的新成绩
    double newScore;
    cin >> newScore;

    // 输出学生和教师的数据
    cout << "Before setting new score:" << endl;
    cout << "Student:" << endl;
    s.display();
    cout << "Teacher:" << endl;
    t.display();

    // 教师设置学生的新成绩
    t.setScore(s, newScore);

    // 输出学生的新数据
    cout << "After setting new score:" << endl;
    s.display();

    return 0;
}
C++面向对象编程:学生和教师类实现

原文地址: https://www.cveoy.top/t/topic/nBHQ 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录