CSDN的各位友友们你们好,今天千泽为大家带来的是
燕山大学-面向对象程序设计实验-实验5 派生与继承:单重派生-实验报告,
接下来让我们一起进入c++的神奇小世界吧,相信看完你也能写出自己的 实验报告!
本系列文章收录在专栏 燕山大学面向对象设计报告中 ,您可以在专栏中找到其他章节
如果对您有帮助的话希望能够得到您的支持和关注,我会持续更新的!
实验五 派生与继承—单重派生
5.1 实验目的
1.理解继承的含义以及声明;
2.理解共有派生、私有派生和保护派生的含义以及使用;
3.理解单派生类中构造函数和析构函数的调用顺序。
5.2 实验内容
5.2.1程序阅读
1.理解下面的程序,并在VC++6.0下运行查看结果,回答程序后面的问题。
#include "iostream"
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();
}
问题一:以上程序有两大错误,试指出来,并改正之?
答:
(1)CBase成员函数print为protected,无法在主函数中直接访问。应该将print设为public。
(2)派生类CDerive无构造函数,无法进行初始化。修改后CDerive类代码如下:
class CDerive : public CBase{
public:
CDerive(int a):CBase(a){
}
void print(){
CBase::print();
cout<<"b="<<b<<endl;
}
private:
int b;
};
2.理解下面的程序,并在VC++6.0下运行查看结果,回答程序后面的问题。
#include "iostream"
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();
}
问题一:以上程序的输出结果是什么,说明为什么?
答:输出为
base structure
base structure
derive structure
a = 1
b,a = 2
c = 3
derive structure
base destructure
base destructure
说明在main中构造CDerive类时,传入的三个参数a,b,c,分别用于直接构造基类CBase,构造成员变量中的CBase类,给CDerive自己的成员变量赋值。因此在print前会有两个base structure和一个derive structure输出。析构时同理。
问题二:①处语句执行完后,d.b.a的值为多少?
答:①处语句执行完后,d.b.a的值为2。
5.2.2 程序设计
1.定义点CPoint类作为基类,在此基础上派生出直线CLine类和圆CCircle类,并要求基类和各派生类具有以下特点:
a.CLine类含有计算直线长度和斜率的成员函数;
b.CCircle类含有计算圆面积的成员函数。
答:
#include<iostream>
#include<cmath>
using namespace std;
class CPoint{
public:
double x,y;
CPoint(double x,double y):x(x),y(y){
}
CPoint():x(0),y(0){
}
void PrintPoint(){
cout<<"点为("<<x<<","<<y<<")"<<endl;
}
};
class CLine:public CPoint{
private:
CPoint p1,p2;
public:
CLine(double x1,double y1,double x2,double y2){
p1.x=x1;
p1.y=y1;
p2.x=x2;
p2.y=y2;
}
void PrintLength(){
cout<<"直线长度:"<<sqrt(pow(p1.x-p2.x,2)+pow(p1.y-p2.y,2))<<endl;
}
void PrintSlope(){
cout<<"直线斜率:"<<(p2.y-p1.y)/(p2.x-p1.x)<<endl;
}
void PrintLine(){
cout<<"直线端点为("<<p1.x<<","<<p1.y<<"),("<<p2.x<<","<<p2.y<<")"<<endl;
}
};
class CCircle:public CPoint{
private:
double r;
public:
CCircle(double x,double y,double r):CPoint(x,y),r(r){
}
void PrintArea(){
cout<<"圆面积:"<< 3.1415926*r*r<<endl;
}
void PrintCircle(){
cout<<"圆心为("<<x<<","<<y<<"),半径为"<<r<<endl;
}
};
int main(){
CPoint a(2,3);
a.PrintPoint();
CLine b(0,0,5,5);
b.PrintLine();
b.PrintLength();
b.PrintSlope();
CCircle c(2,2,1);
c.PrintCircle();
c.PrintArea();
return 0;
}
友友们多动手实践一下吧!