补充内容3多态ppt课件.ppt
文本预览下载声明
void f(container *p) { cout 表面积: p-surface_area() endl; cout “体积: p-volume() endl; } void main() { cubt obj1(5); sphere obj2(5); cylinder obj3(5,5); cout “正方体”endl; f(obj1); cout“球体“endl; f(obj2); cout“圆柱体”endl; f(obj3); } * 面向对象程序设计的一般目标就是编写通用的可扩展的代码。 如:用代码体管理指向基类的指针,所以如果想增加一个新类来扩充程序(比如从shape中派生出 rhomboid),代码体部分并不受影响。 * 总结:面向对象程序设计的主要优点是: 与客观世界的组成方式和人类习惯的思维方式一致 可重用性好(类、继承) 可维护性好(封装性) 可扩展性好(多态性) * class Point { public: Point(int x1,int y1){x=x1;y=y1;} Point(const Point p){x=p.x;y=p.y;} void setp(int x1,int y1){x=x1;y=y1;} void move(int x1,int y1){x=x+x1;y=y+y1;} private: int x,y; }; class Shape { public: Shape(int c){ color=c; } void setcolor(int c){ color=c; } virtual void display()=0; protected: int color; }; * class Rect:public Shape { public: Rect(int c,int x1,int y1,int w1,int h1) : Shape(c),topleft(x1,y1) {w=w1; h=h1;} void display(){ coutRectendl;} protected: Point topleft; int w,h; }; class Ellipse:public Shape { public: Ellipse(int c,int x,int y,int rr1,int rr2): Shape(c),p(x,y) {r1=rr1;r2=rr2;} void display(){coutEllipseendl;} protected: Point p; int r1,r2; }; * class Triangle :public Shape { public: Triangle(int c,int x1,int y1,int x2,int y2,int x3,int y3) : Shape(c),p1(x1,y1),p2(x2,y2),p3(x3,y3) { } void display(){coutTriangleendl;} protected: Point p1,p2,p3; }; void main() { Rect r(1,0,0,3,4); Ellipse e(1,4,5,2,3); Triangle t(1,0,0,2,3,6,7); Shape *p[3]; p[0]=r; p[1]=e; p[2]=t; for(int i=0;i3;i++) p[i]-display(); } * * * #includeiostream.h class unstudent { protected: int no; char name[10]; int fee1,fee2,fee3,fee4,fee; public: void calfee() { cout 学号:; cin no; cout 姓名:; cin name; fee1 = 4800; fee2 = 1100; fee3 = 400; fee4 = 200; fee = fee1 + fee2 + fee3 + fee4; } void disp() { cout 学费: fee1 endl; cout 住宿费: fee2 endl; cout 书报费: fee3 endl; cout 其他: fee4 endl; cout 总费用: fee endl; } }; class qraduate : public unstuden
显示全部