例15.7 派生类的构造函数。
#include<string.h>
#include <iostream.h>
class stud//声明基类
{protected,//保护部分
int num;
char name[10];
char sex ;
public,//公用部分
stud(int n,char nam[],char s ) //基类构造函数
{num=n;
strcpy(name,nam);
sex=s; }
~stud( ) { } //基类析构函数
};
class student,public stud //声明公用派生类student
{ private,//派生类的私有数据
int age;
char addr[30];
public:
student(int n,char nam[],char s,int a,char ad[]),stud(n,nam,s)
//派生类构造函数
{age=a; //在此处只对派生类新增的变量初始化
strcpy(addr,ad);
}
void show( )
{ cout<<"num,"<<num<<endl;
cout<<"name,"<<name<<endl;
cout<<"sex,"<<sex<<endl;
cout<<"age,"<<age<<endl;
cout<<"address,"<<addr<<endl;}
~student ( ) { } //派生类析构函数
};
void main( )
{student a(10010,"Wang-li",′f′,19,"115 Beijing Road,Shanghai");
student b(10011,"Zhang-fun",′m′,21,"213 Shanghai Road,Beijing");
a.show( ); //输出第一个学生的数据
b.show( ); //输出第二个学生的数据
}
#include<string.h>
#include <iostream.h>
class stud//声明基类
{protected,//保护部分
int num;
char name[10];
char sex ;
public,//公用部分
stud(int n,char nam[],char s ) //基类构造函数
{num=n;
strcpy(name,nam);
sex=s; }
~stud( ) { } //基类析构函数
};
class student,public stud //声明公用派生类student
{ private,//派生类的私有数据
int age;
char addr[30];
public:
student(int n,char nam[],char s,int a,char ad[]),stud(n,nam,s)
//派生类构造函数
{age=a; //在此处只对派生类新增的变量初始化
strcpy(addr,ad);
}
void show( )
{ cout<<"num,"<<num<<endl;
cout<<"name,"<<name<<endl;
cout<<"sex,"<<sex<<endl;
cout<<"age,"<<age<<endl;
cout<<"address,"<<addr<<endl;}
~student ( ) { } //派生类析构函数
};
void main( )
{student a(10010,"Wang-li",′f′,19,"115 Beijing Road,Shanghai");
student b(10011,"Zhang-fun",′m′,21,"213 Shanghai Road,Beijing");
a.show( ); //输出第一个学生的数据
b.show( ); //输出第二个学生的数据
}