![]() |
#2
东海一鱼2010-08-09 18:22
|

//例11.6 包含子对象的派生类构造函数--谭浩强《 C++ 程序设计 》p367.
#include <iostream>
#include <string>
using namespace std;
class Student //声明基类
{
public: //公用部分
Student( int n, string nam) //基类构造函数
{ num = n;
name = nam;
}
void display( ) //成员函数,输出基类数据成员
{ cout << "num:" << num << endl << "name:"<< name << endl;}
protected: //保护部分
int num;
string name;
};
class Student1:public Student //声明公用派生类 Student1
{
public:
Student1( int n,string nam,int n1,string nam1,int a,string ad):
Student( n, nam),monitor( n1,nam1) //派生类构造函数
{
age = a;
addr = ad;
}
void show( )
{
cout << "This student is:" << endl;
display( ); //输出 num 和 name
cout << "age:" << age << endl; //输出 age
cout << "address:"<< addr << endl << endl; //输出 addr
}
void show_monitor( ) //成员函数,输出子对象
{
cout << endl << "Class mornitor is:" << endl;
monitor.display( ); //调用基类成员函数
}
private: //派生类私有数据
Student monitor; //定义子对象班长
int age;
string addr;
};
int main( )
{
Student1 stud1( 10010,"wang - li",10001,"Li - sun",19,"115 Beijing Road, Shanghai");
stud1.show( ); //输出学生数据
stud1.show_monitor( ); //输出子对象数据
system("pause");
return 0;
}
/*所谓子对象,其实是派生类的一个数据成员,其特殊性是它是属于基类的对象之一。派生类对象 stud1
通过类内成员函数 show_monitor( )(派生类成员函数)调用基类公用成员函数 display( ) 达到输出 num
和 name 的目的。
派生类构造函数的任务有三:
一、对基类数据成员初始化;
二、对子对象数据成员初始化;
三、对派生类数据成员初始化;
*/
如果你觉得有用,需要拷贝,请注明出处:http://bbs.bccn.net #include <iostream>
#include <string>
using namespace std;
class Student //声明基类
{
public: //公用部分
Student( int n, string nam) //基类构造函数
{ num = n;
name = nam;
}
void display( ) //成员函数,输出基类数据成员
{ cout << "num:" << num << endl << "name:"<< name << endl;}
protected: //保护部分
int num;
string name;
};
class Student1:public Student //声明公用派生类 Student1
{
public:
Student1( int n,string nam,int n1,string nam1,int a,string ad):
Student( n, nam),monitor( n1,nam1) //派生类构造函数
{
age = a;
addr = ad;
}
void show( )
{
cout << "This student is:" << endl;
display( ); //输出 num 和 name
cout << "age:" << age << endl; //输出 age
cout << "address:"<< addr << endl << endl; //输出 addr
}
void show_monitor( ) //成员函数,输出子对象
{
cout << endl << "Class mornitor is:" << endl;
monitor.display( ); //调用基类成员函数
}
private: //派生类私有数据
Student monitor; //定义子对象班长
int age;
string addr;
};
int main( )
{
Student1 stud1( 10010,"wang - li",10001,"Li - sun",19,"115 Beijing Road, Shanghai");
stud1.show( ); //输出学生数据
stud1.show_monitor( ); //输出子对象数据
system("pause");
return 0;
}
/*所谓子对象,其实是派生类的一个数据成员,其特殊性是它是属于基类的对象之一。派生类对象 stud1
通过类内成员函数 show_monitor( )(派生类成员函数)调用基类公用成员函数 display( ) 达到输出 num
和 name 的目的。
派生类构造函数的任务有三:
一、对基类数据成员初始化;
二、对子对象数据成员初始化;
三、对派生类数据成员初始化;
*/