2023-6-8作业补
Person类,私有成员(姓名,年龄,身高,体重),公有成员方法(有参构造函数、析构函数、show函数)stu类,继承/派生自Person类,私有成员(成绩,班级),公有成员方法(有参构造函数、析构函数、show函数),实例化一个Stu对象并调用shou函数。
#include<iostream>
using namespace std;
//Person类
class Person
{
string name;int age;int high;
public:
//在子类的有参构造内调用父类
Person(string name,int age,int high):name(name),age(age),high(high)
{cout<<"Person or parameter with constructor"<<endl;}
Person(){cout<<"Person non-parameter constructor"<<endl;}
~Person(){cout<<"Per or destructor"<<endl;}
void show()
{
cout<<name<<"\t"<<age<<"\t"<<high<<endl;
cout<<"Per or show"<<endl;
}
};
class Stu:public Person
{
int score;
int class_;
public:
//父类有参构造
Stu():Person("shang",18,100){cout<<"Stu or non-parameter constructor"<<endl;}
~Stu(){cout<<"Stu or destructor"<<endl;}
//当父类定义有参构造时,初始化子类的有参列表,显示调用父类有参构造。
Stu(int score,string name,int age,int high,int class_):Person(name,age,high)
{
this->score=score;
this->class_=class_;
cout<<"Stu or construct with parameter"<<endl;
}
void show()
{
cout<<"Score="<<score<<"\t"<<"class_"<<class_<<endl;
cout<<"Stu or show"<<endl;
}
};
int main()
{
//实例化Stu对象
Stu stu1(80,"zhangsan",18,100,3);
stu1.show();
stu1.Person::show();
return 0;
}