Design a class people with protected data members: age (age, integer), name (name, string), behavior members: two constructors (one has no parameters, the other has parameters); destructor; void setValue( int m, string str) assigns values to age and name; void display() outputs age and name.
Design a student class student, a public inheritance class people, with private members: ID (student number, integer), behavior members: two constructors (one without parameters, the other with parameters); destructor; void setID(int m) Assign a value to the ID; void displayID() outputs the ID.
Define the student object in the main function, assign values to the object initialization or call setValue() and setID() to assign values, and output student information.
#include<iostream>
using namespace std;
//定义类
class People{
protected:
int age;//age(年龄,整型)
string name;//name(姓名,string)
public:
People(){};//默认构造函数
People(int a,string n){//有参数的构造函数
age = a;
name = n;
}
~ People(){};//析构函数
void setValue(int m,string str){
age = m;
name = str;
}
virtual void display() const = 0;//纯虚函数
};
class Student : public People{//Student类公有继承People类
private:
int studentID;//studentID(学号,整型)
public:
Student(){};//默认构造
Student(int age,string name,int studentID):People(age,name){//含参构造
this->studentID = studentID;
}
~Student(){};//析构
void setID(int m){//给studentID赋值
this->studentID = m;
}
void display() const{//覆盖基类的虚函数,输出学生的姓名、年龄、学号
cout<<name<<","<<age<<","<<studentID<<endl;
}
};
void fun(People *ptr){//定义抽象类的指针和引用
ptr->display();
}
int main(){
//定义对象
People *people;
Student student;
int age;
string name;
int id;
cout<<"请输入年龄、姓名"<<endl;
cin>>age>>name;
people = &student;
people->setValue(age,name);
cout<<"请输入学生学号"<<endl;
cin>>id;
student.setID(id);
cout<<"输出信息:"<<endl;
fun(&student);
return 0;
}