设计一个类people,有保护数据成员:age(年龄,整型),name(姓名,string),行为成员:两个构造函数(一个无参,另一个有参数);析构函数;void setValue(int m, string str)给age和name赋值;void display()输出age和name。
设计一个学生类student,公有继承类people,有私有成员:ID(学号,整型),行为成员:两个构造函数(一个无参,另一个有参数);析构函数;void setID(int m)给ID赋值;void displayID()输出ID。
在main函数定义学生对象,给对象初始化赋值或调用setValue()和setID()赋值,并输出学生的信息。
#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;
}