一、实验目的和要求
|
二、实验环境(软、硬件及条件) 一台安装有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(); }
|