实验指导(C++面向对象部分)

发布时间 : 星期日 文章实验指导(C++面向对象部分)更新完毕开始阅读

list2.print();

cout<<\ list2.print(); list2.reverse(); cout<<\ list2.print();

cout<<\}

【思考题】

1.看看自己还能给实验题目2添加些什么样的操作? 2.如果用静态成员函数访问非静态数据成员,可以么?

实验三 类的继承

【实验类型】验证性 【实验要求】必做

【实验目的】

1.了解类的继承的概念和按继承方式的继承分类及各种继承方式的特点。 2.了解并掌握派生类对象的构造和析构过程。 3.了解并掌握单继承,多继承的定义方式。 4.了解多继承情况下产生的二义性及解决办法。

5.了解虚基类的定义,原理和用法,了解存在虚基类的情况下,派生类对象的构造和析构过程。 【实验内容】

实验题1.定义一个继承与派生关系的类体系,在派生类中访问基类成员。先定义一个点类,包含x,y坐标数据成员,显示函数和计算面积的函数成员;以点为基类派生一个圆类,增加表示半径的数据成员,重载显示和计算面积的函数;定义一个线段类,以两个点类对象作数据成员,定义显示、求面积及长度函数,线段类采用聚合方式,因为有两个端点,不能用派生。

实验题2.由汽车类派生出轿车类和卡车类,再由轿车类和卡车类多重派生出皮卡类。所谓皮卡指的是轿车的后备箱改为卡车似的后厢,可以兼运少量货物。汽车类可以说明为虚基类,以避免在皮卡类中出现两组汽车类的数据,请与未说明为虚基类的情况对比。

【参考程序】 实验题1参考程序 #include #include using namespace std; #define PI 3.14159 class Point{

friend class Line; protected:

double x, y ; public:

Point(){x = 0 ; y = 0 ; }

Point(double xv,double yv){ x = xv; y = yv; } double Area(){return 0;} void Show() {

cout<<\ } };

class Circle :public Point{ double radius; public:

Circle(){ x = 0; y = 0; radius = 0; }

Circle(double xv,double yv,double vv):Point(xv,yv){ //调用基类构造函数 radius = vv; }

Circle(Circle & cir):Point(cir){ //按赋值兼容规则cir可为Point构造函数的实参

radius=cir.radius; }

Circle & operator=(Circle & cir){

this->Point::operator=(cir); //在派生类中重载复制赋值操作符有固定的标准格式

radius=cir.radius; return *this; }

double Area(){

return PI*radius*radius; }

void Show(){ //可以直接访问基类的数据成员

cout<<\ } };

class Line{

Point start,end; //对象成员 public:

Line():start(0,0),end(0,0){ } //注意对象成员初始化的方法 Line(double xv1,double yv1,double xv2,double yv2) : start(xv1,yv1),end(xv2,yv2){ } double GetLength() { return

sqrt((start.x-end.x)*(start.x-end.x)+(start.y-end.y)*(start.y-end.y)); }

double Area(){return 0;} void Show(){

cout<<\ start.Show();

cout<<\ end.Show(); } };

int main(){

Point pt(0,0);

Circle cl1(100,100,10),cl2(cl1),cl3; Line ln1(0,0,100,100);

cout<<\点面积:\

pt.Show();

cout<<\圆面积:\ cl1.Show();

cout<<\圆面积:\ cl2.Show(); cl3=cl1;

cout<<\圆面积:\ cl3.Show();

cout<<\线面积:\线长度:\ ln1.Show(); return 0; }

实验题2参考程序 #include #include

using namespace std; class automobile{ protected:

string model; //型号 double cylinders_capability; //排量 int wheels; //轮数 double price; //价格 public:

automobile(string mod=\ model=mod;

cylinders_capability=cl; wheels=wh; price=pr; }

void display(){

cout<<\汽车型号:\排量:\升\

cout<<\轮数:\价格:\ } };

class car:public virtual automobile{ protected:

int seats; //座位数

int safeguards; //保护措施数量 public:

car(string mod=\saf=0):automobile(mod,cl,wh,pr){ seats=st;

safeguards=saf;

联系合同范文客服:xxxxx#qq.com(#替换为@)