C++程式設計實踐上機指導書?

(第九次)

專業 軟體工程

班級 軟體131

學號 2013416120

姓名 康育嘉

瀋陽工程學院資訊學院

實踐成績評價說明

1)上機前充分準備實踐材料,對上機內容有程式草稿。(10分)

2)獨立完成實踐任務,對實踐過程非常清晰。(30分)

3)認真理解知識點,能夠與理論知識相結合。(10分)

4)在機房遵守上機守則,接受實踐指導教師的監督與管理。(20分)

5)認真填寫實踐指導書,寫出實踐小結。(10分)

6)在實踐中具備一定的創新思想,能夠主動與指導教師探討。(5分)

7)加大實踐工作量,主動完成實踐指導書中的選做題目。(5分)

8)掌握程式除錯的方法,認真完成程式除錯工作,使程式能夠執行(10分)。

上機九虛擬函式

一、目的

1.掌握用函式成員實現運算子過載的方法;

2.掌握用友元函式實現運算子過載的方法;

3.掌握虛擬函式的概念及應用。

二、要求:

1. 在上課之前,每一個同學必須將題目、程式編寫完畢,做好充分的準備。

2. 所有環節均由每位同學獨立完成,嚴禁抄襲他人結果。

三、步驟和內容

1、三維座標類物件之間的直接運算。

三維座標類有資料成員x、y、z,物件間運算時要求通過函式成員實現“+”、前置“--”、“= =”運算子的過載,通過友元函式實現後置“--”、“+=”、“>>”和“<<”運算子的過載,實現三維座標類物件間的直接運算。main()完成物件的定義和有關運算子過載函式的測試。

(提示:1)書中P313例8-3是對二維座標的過載,首先閱讀它,看看對編寫三維座標有何啟發。2)插入符函式的一般形式:

ostream &operator<<(ostream &函式的流, 類名 &物件名){

return 函式的流;

}

2、由二維座標點類作為基類派生出圓類;再由圓類作為基類派生出圓柱體類(通過虛擬函式完成輸出)。

四、思考題

1、體會函式過載的兩種方法。

五、結果分析

1.

#include

using namespace std;

class Point

{

public:

Point(int xx=0,int yy=0,int zz=0):x(xx),y(yy),z(zz){}

Point operator+(const Point &p)const

{

return Point(x+p.x,y+p.y,z+p.z);

}

Point operator--()

{

--x;

--y;

--z;

return *this;

}

bool operator==(const Point &p1)

{

if(x==p1.x&&y==p1.y&&z==p1.z)

return true;

return false; }

friend Point operator--(Point p,int)

{

return Point(--p.x,--p.y,--p.z);

}

friend void operator+=( Point &p1, Point &p2)

{

p1.x+=p2.x;

p1.y+=p2.y;

p1.z+=p2.z;

}

friend ostream & operator<<(ostream &out,const Point &p)

{ out<<"("<

return out;

}

friend istream& operator>>(istream&in,const Point &p)

{

in>>p.x>>p.y>>p.z;

return in;

}

private:

int x,y,z;

};

int main()

{

Point p1(5,3,2);

Point p2(1,5,4);

Point p3;

cout<<

"p1: "

<

cout<<"p2: "

<

p3=p1+p2;

cout<<"p3=p1+p2: "

<

--p1;

cout<<"--p1: "<

if(p1==p2)

cout<<"YES"<

else

cout<<"NO"<

p1+=p2;

cout<<"p1+=p2: "<

return 0;

}

2.

#include

#define PI 3.1415

using namespace std;

class Point {

public: Point(int xx=0,int yy=0):x(xx),y(yy){}

int GetX(){return x;}

int GetY(){return y;}

virtual void show()=0;

private:

int x,y; };

class Circle:public Point

{

public: Circle(int xx=0,int yy=0,int r=0):Point(xx,yy),radius(r){}

int GetR()

{

return radius;

}

float Getarea()

{

float area;

area=static_cast (2*PI*radius);

return area;

}

void show()

{

cout<<"圓心座標: ("<

cout<<"圓的半徑: "<

cout<<"圓的面積: "<

}

private:

int radius;

};

class Cylinder:public Circle

{

public:

Cylinder(int xx=0,int yy=0,int r=3,int h=6):Circle(xx,yy,r),height(h){}

int GetH()

{

return height;

}

int GetV()

{

float v;

v=static_cast (Circle::Getarea()*height);

return v;

}

void show()

{ cout<

Circle::show();

cout<<"圓柱體的高度: "<

cout<<"圓柱體的體積: "<

}

private:

int height;

};

int main()

{

Point *pp;

Circle c(0,0,6);

pp=&c;

pp->show();

Cylinder v(0,0,8,9);

pp=&v;

pp->show();

return 0;

}

六、指導教師評閱成績

相關問題答案