2023 4 21
注意double类型相运算的也要是double类型
如上例若把a变量更改为int类型则会导致结果出错
#include<iostream> #include<string> using namespace std; class people{ protected: int age; string name; public: people(){} people(int a,string str){ age=a; name=str; } ~people(){} void setvalue(int m,string str){ age=m; name=str; } virtual void display()=0; }; class student:public people { private: int studentid; public: student(){} student(int a,string str,int n):people(a,str){ studentid=n; } ~student(){} void setid(int m){ studentid=m; } void display(){ cout<<"姓名:"<<name<<"\t"<<"年龄:"<<age<<"\t"<<"ID:"<<studentid<<endl; } }; class teacher:public people { private: int teacherid; public: teacher(){} teacher(int a,string str,int n):people(a,str){ teacherid=n; } ~teacher(){} void setid(int m){ teacherid=m; } void display(){ cout<<"姓名:"<<name<<"\t"<<"年龄:"<<age<<"\t"<<"ID:"<<teacherid<<endl; } }; int main(){ int a1,a2; string str1,str2; int n,m; student stu1; teacher tea1; people *p1; p1=&stu1; cout<<"请输入学生的姓名,年龄,学号"<<endl; cin>>str1>>a1>>n; cout<<"请输入教师的姓名,年龄,学号"<<endl; cin>>str2>>a2>>m; p1->setvalue(a1,str1); stu1.setid(n); p1->display(); p1=&tea1; p1->setvalue(a2,str2); tea1.setid(m); p1->display(); return 0; }