3.派生类的构造函数和析构函数:
派生类构造函数:
定义原则:除了对派生类数据成员初始化外,还要对基类的数据成员初始化。
解决思路:执行派生类构造函数时,调用基类构造函数(基类构造函数不能被继承)。
派生类构造函数的一般形式:
派生类构造函数名(总参数列表):
基类构造函数名(参数表)
{
派生类中新增数据成员初始化语句;
}
2点说明:
①(总参数列表)为派生类构造函数定义的形参,需要参数类型说明;
②(参数表)为调用基类构造函数传递的实参,不需要说明参数类型;
派生类构造函数的特殊形式:
① 当不需要对派生类新增成员初始化时,派生类构造函数体可以为空,而构造函数仅仅用于完成向基类构造函数传递参数的任务。
Student1(int n,string nam,char s):Student(n,nam,s){}
② 如果基类中没有定义构造函数,或只定义了不带参数或带缺省参数的构造函数,则派生类构造函数中可以不写基类构造函数。
Student1(int a,string ad)
{ age=a;addr=ad;}
③ 如果满足上面2种情况,可以不必显式地定义派生类构造函数。
④ 如果基类中既有不带参数的、又有带参数的构造函数,则在派生类构造函数中可以包含、也可以不包含基类的构造函数。
//例,显示学生全部情况
#include< iostream >
#include< string >
using namespace std;
class Student
{
private:
int num;
string name;
char sex;
public:
Student(int n,string nam,char s)
{
num=n;
name=nam;
sex=s;
}
void display();
~Student(){}
};
class Student1 : public Student
{
private:
int age;
string addr;
public:
Student1(int n,string nam,char s,int a,string ad):Student(n,nam,s)
{
age=a;
addr=ad;
}
void display_1();
};
void Student::display()
{
cout<<"num:"<<num<<endl;
cout<<"name:"<<name<<endl;
cout<<"sex:"<<sex<<endl;
}
void Student1::display_1()
{
// cout<<"num:"<<num<<endl;
//cout<<"name:"<<name<<endl;
//cout<<"sex:"<<sex<<endl;
display();
cout<<"age:"<<age<<endl;
cout<<"address:"<<addr<<endl<<endl;
}
int main()
{
Student1 st1(10010,"Wang-li",'f',19,"Beijing…");
Student1 st2(10012,"Xv-lin",'m',20,"Shenzhen…");
st1.display_1(); //输出第一个学生的数据
st2.display_1(); //输出第二个学生的数据
return 0;
}
或者 把class Student中private改为protected 然后将display_1()函数改动,如下所示:
//例,显示学生全部情况
#include< iostream >
#include< string >
using namespace std;
class Student
{
protected:
int num;
string name;
char sex;
public:
Student(int n,string nam,char s)
{
num=n;
name=nam;
sex=s;
}
void display();
~Student(){}
};
class Student1 : public Student
{
private:
int age;
string addr;
public:
Student1(int n,string nam,char s,int a,string ad):Student(n,nam,s)
{
age=a;
addr=ad;
}
void display_1();
};
void Student::display()
{
cout<<"num:"<<num<<endl;
cout<<"name:"<<name<<endl;
cout<<"sex:"<<sex<<endl;
}
void Student1::display_1()
{
cout<<"num:"<<num<<endl;
cout<<"name:"<<name<<endl;
cout<<"sex:"<<sex<<endl;
cout<<"age:"<<age<<endl;
cout<<"address:"<<addr<<endl<<endl;
}
int main()
{
Student1 st1(10010,"Wang-li",'f',19,"Beijing…");
Student1 st2(10012,"Xv-lin",'m',20,"Shenzhen…");
st1.display_1(); //输出第一个学生的数据
st2.display_1(); //输出第二个学生的数据
return 0;
}