文档详情

C++程序设计 第二版 杨长兴 第九章.ppt

发布:2017-05-31约1.07万字共31页下载文档
文本预览下载声明
第9章 多态性和虚函数 9.1 多态性的概念 多态性是指不同类的对象对于同一消息的处理具有不同的实现。 多态性在C++中表现为同一形式的函数调用,可能调用不同的函数实现。从系统实现的角度看,C++的多态性分为两类,一类称为编译时刻多态性,另一类称为运行时刻多态性,也称动态多态性。 9.1.1 编译时刻的多态性 C++编译时多态性通过重载(函数重载和运算符重载)来实现 【例9.1】 编译时刻的多态性——运算符重载:下面这段程序建立Rectangle类和Cuboid类,并重载运算符“+=”,使之能用于相应类对象的运算。 #include iostream using namespace std; class Rectangle //定义矩形类 { public: Rectangle(double w=0,double l=0); //缺省构造函数 void set_wl(double w,double l); double get_w()const; double get_l()const; double area(); ~Rectangle() {}; //析构函数 Rectangle operator+=(Rectangle rec_add) //重载运算符+= { width += rec_add.width; length += rec_add.length; return *this; //返回当前对象 } protected: int width; int length; }; Rectangle::Rectangle(double w, double l):width(w),length(l){} void Rectangle::set_wl(double w,double l) { width=w; length=l; } double Rectangle::get_w() const { return width; } double Rectangle::get_l() const { return length; } double Rectangle::area() { return width*length; } class Cuboid:public Rectangle //定义长方体类 { public: Cuboid(double w=0,double l=0,double h=0); void set_wlh(double w,double l,double h); double get_h() const; double area(); Cuboid operator+=(Cuboid cub_add) { width += cub_add.width; length += cub_add.length; height += cub_add.height; return *this; //返回当前对象 } protected: double height; }; Cuboid::Cuboid(double w,double l,double h):Rectangle(w,l),height(h){ } void Cuboid::set_wlh(double w,double l,double h) { width=w;length=l;height=h; } double Cuboid::get_h() const { return height; } double Cuboid::area() { return 2*(width*length+width*height+length*height); } //求长方体的表面积 int main() { Rectangle rec1(1,2); Rectangle rec2; Cuboid cub1(1,2,3); Cuboid cub2; rec2.set_wl(2,4); cub2.set_wlh(5,10,15); coutrec1:(width=rec1.get_w(),length=rec1.get_l() )endl;
显示全部
相似文档