816306411_5_实验七 继承与派生

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

实验七继承与派生

【实验目的】

1、掌握继承的概念。

2、理解派生类与基类的关系。

3、理解不同的继承类型。

4、掌握继承下的构造函数和析构函数。

5、掌握单继承和多继承使用方法。

6、理解静态成员。

【实验内容】

1、上机分析下面程序,理解继承下构造函数和析构函数的执行顺序。

#include

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 <

}

~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

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<

};

void main()

{

Derived d;

d.Init(5,9);

d.output();

}

3、在下面一段类定义中,Derived类公有继承了基类Base。需要填充的函数有注释内容给出了功能。并补充定义主函数,完成派生类对象的定义。

#include

using namespace std;

class Base{

private:

int mem1,mem2;

public:

Base(int m1,int m2)

{mem1=m1;mem2=m2;}

void output(){cout<

};

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<

};

Derived::Derived(int m1,int m2,int m3): (2)

{ (3) ;}

4、上机分析下面程序,掌握静态成员

# include

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<

delete p;

cout<

return 0;

}

5、设计一个具有继承和派生的类,分析程序输出结果,理解类的继承与派生。参考程序:

#include

using namespace std;

class A

相关文档
最新文档