实验七继承与派生
【实验目的】
1、掌握继承的概念。
2、理解派生类与基类的关系。
3、理解不同的继承类型。
4、掌握继承下的构造函数和析构函数。
5、掌握单继承和多继承使用方法。
6、理解静态成员。
【实验内容】
1、上机分析下面程序,理解继承下构造函数和析构函数的执行顺序。
#include <iostream>
using namespace std;
class A
{
public:
A()
{
cout<<"Constructor1_A"<< x << endl;
}
A( int m ) : x( m )
{
cout<<"Constructor2_A"<< x << endl;
}
~A()
{
cout<<"Destructor_A"<< x << endl;
}
private:
int x;
};
class B : public A
{
public:
B()
{
cout<<"Constructor1_B"<< y << endl;
}
B( int m, int n, int l ) : A( m ), a( n ), y( l )
{
cout<<"Constructor2_B"<< y <<endl;
}
~B()
{
cout<<"Destructor_B"<< y << endl;
}
private:
A a;
int y;
};
int main()
{
B b1, b2(5,6,7);
return 0;
}
2、在下面一段类定义中,Derived类是有直接基类Base1和Base2所公有派生的,Derived 类包含有两个间接基类Base,在初始化函数Init中,需要把x1和x2的值分别赋给属于基类Base1的x成员和属于基类Base2的x成员。
#include<iostream>
using namespace std;
class Base{
protected:
int x;
public:
Base(){x=0;}
};
class Base1:public Base{
public:
Base1(){}
};
class Base2:public Base{
public:
Base2(){}
};
class Derived: (1)
{
public:
Derived(){}
void Init(int x1,int x2){
(2) ;
(3) ;
}
void output(){cout<<Base1::x<<' '<<Base2::x<<endl;}
};
void main()
{
Derived d;
d.Init(5,9);
d.output();
}
3、在下面一段类定义中,Derived类公有继承了基类Base。
需要填充的函数有注释内容给出了功能。
并补充定义主函数,完成派生类对象的定义。
#include<iostream>
using namespace std;
class Base{
private:
int mem1,mem2;
public:
Base(int m1,int m2)
{mem1=m1;mem2=m2;}
void output(){cout<<mem1<<" "<<mem2<<endl;}
};
class Derived:public Base
{
private:
int mem3;
public:
//构造函数,由m1和m2分别初始化mem1和mem2,由m3初始化mem3 Derived(int m1,int m2,int m3);
//输出mem1,mem2和mem3数据成员的值
void output(){
(1) ;
cout<<mem3<<endl;}
};
Derived::Derived(int m1,int m2,int m3): (2)
{ (3) ;}
4、上机分析下面程序,掌握静态成员
# include <iostream>
using namespace std;
class sample
{
public:
sample ( ){ ++n; }
static int HM(){ return n; }
~sample ( ){ --n; }
private:
static int n;
};
int sample::n = 10;
int main()
{
sample c1,c2;
sample *p = new sample();
cout<<sample::HM()<<endl;
delete p;
cout<<sample::HM()<<endl;
return 0;
}
5、设计一个具有继承和派生的类,分析程序输出结果,理解类的继承与派生。
参考程序:
#include <iostream>
using namespace std;
class A
{
public:
void f(int i)
{cout<<i<<endl;}
void g()
{cout<<"g\n";}
};
class B:A
{
public:
void h(){cout<<"h\n";}
A::f;
};
void main()
{
B d1;
d1.f(6);
d1.g();
d1.h();
}
问题:
⑴、执行该程序时,哪个语句会出现编译错误?为什么?
⑵、去掉出错语句后,执行该程序后输出结果如何?
⑶、程序中派生类B是从基类A中继承来的,这种缺省继承方式是哪种继承方式?
⑷、派生类B中,A::f的含意是什么?
⑸、将派生类B的继承改为公有继承方式该程序将输出什么结果?
6、定义一个车类(Vehicle),含有数据成员wheelnum,speed。
派生出自行车类(Bicycle),
增加成员height;派生出汽车类(Car),增加成员seatnum。
要求各类提供必要的构造函数初始化基本成员,并添加显示输出的成员函数。
编写主函数,测试这个层次结构,输出自行车和汽车的相关信息。