C++实验5_1继承与派生(1)

一、实验目的和要求

 

二、实验环境(软、硬件及条件)

一台安装有Visual C++ 6.0的计算机

三、实验步骤

1.阅读下面的程序,找出其中的错误并改正,使之能正常输出CBase的私有成员a和CDerive 的私有成员b的值。

#include "iostream.h"

class CBase

{

public:

CBase(int a)

:a(a)

{

}

protected:

void print()

{

cout<<"a="<<a<<endl;

}

private:

int a;

};

class CDerive : public CBase

{

public:

void print()

{

CBase::print();

cout<<"b="<<b<<endl;

}

private:

int b;

};

void main()

{

CDerive d;

d.print();

CBase b;

b.print();

}

2、阅读程序,回答下面的问题。

#include "iostream.h"

class CBase

{

public:

CBase(int a)

:a(a)

{

cout<<"base structure"<<endl;

}

~CBase()

{

cout<<"base destructure"<<endl;

}

void print()

{

cout<<"a="<<a<<endl;

}

protected:

int a;

};

class CDerive : public CBase

{

public:

CDerive(int a, int b,int c)

:CBase(a),b(b),c(c)

{

cout<<"derive structure"<<endl;

}

~CDerive()

{

cout<<"derive destructure"<<endl;

}

void print()

{

CBase::print();

// cout<<"b.a="<<b.a<<endl;  //---------------------------

cout<<"c="<<c<<endl;

}

private:

CBase b;

int c;

};

void main()

{

CDerive d(1,2,3);

d.print();

}

问题1:写出该程序的运行结果。

问题2:若将①处的注释去掉,该程序能否正常运行?为什么?

3、请设计一个点CPoint类作为基类,从CPoint类派生出圆CCircle类,要求CCircle类含有计算圆面积的成员函数,并编写主函数测试运行情况。

四、实验中遇到的问题及解决

 

 

 

 

五、实验结果及分析

1.

#include "iostream.h"

class CBase

{

public:

CBase(){}

void print()

{

cout<<"a="<<a<<endl;

}

private:

int a;

};

class CDerive : public CBase

{

public:

CDerive(){}

void print()

{

CBase::print();

cout<<"b="<<b<<endl;

}

private:

int b;

};

void main()

{

CDerive d;

d.print();

CBase b;

b.print();

}

2.

(1)

base structure

base structure

derive structure

a=1

c=3

derive destructure

base destructure

base destructure

(2)

不能正常运行。因为a是基级的保护成员数据,而Cderive的继承是公有继承,只能继承a,但是不能访问运用a。

3.

#include<iostream>

using namespace std;

class CPoint

{

public:

double r;

void display(double i){r=i;cout<<"a="<<r<<endl;}

};

class CCircle:public CPoint  

{

public:

 area(){double s;

s=r*3.14;

cout<<"s="<<s<<endl;

}

};

void main()

{

CCircle n;

n.display(5);

n.area();

}

 

 

  • 1
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值