嵌入式Linux下C 程序设计--08多态运算符重载 虚函数抽象类课件.ppt

嵌入式Linux下C 程序设计--08多态运算符重载 虚函数抽象类课件.ppt

抽象类 作用 抽象类为抽象和设计的目的而声明,将有关的数据和行为组织在一个继承层次结构中,保证派生类具有要求的行为。 对于暂时无法实现的函数,可以声明为纯虚函数,留给派生类去实现。 注意 抽象类只能作为基类来使用。 不能声明抽象类的对象。 构造函数不能是虚函数,析构函数可以是虚函数。 例如 #include iostream using namespace std; class Base1 { //基类Base1定义 public: virtual void display() const = 0;//纯虚函数 }; class Base2: public Base1 { //公有派生类Base2定义 public: void display() const { //覆盖基类的虚函数 cout Base2::display() endl; } }; class Derived: public Base2 { //公有派生类Derived定义 public: void display() const { //覆盖基类的虚函数 cout Derived::display() endl; } }; void fun(Base1 *ptr) { ptr‐display();//对象指针‐成员名 } intmain() {//主函数 Base2 base2;//定义Base2类对象 Derived derived;//定义Derived类对象 fun(base2);//用Base2对象的指针调用fun函数 fun(derived);//用Derived对象的指针调用fun函数 return 0; } 虚析构函数 为什么需要虚析构函数? 可能通过基类指针删除派生类对象; 如果你打算允许其他人通过基类指针调用对象的析构函数(通过delete这样做是正常的),就需要让基类的析构函数成为虚函数,否则执行delete的结果是不确定的。 静态绑定与动态绑定 绑定 程序自身彼此关联的过程,确定程序中的操作调用与执行该操作的代码间的关系。 静态绑定 绑定过程出现在编译阶段,用对象名或者类名来限定要调用的函数。 动态绑定 绑定过程工作在程序运行时执行,在程序运行时才确定将要调用的函数。 静态绑定例 #includeiostream using namespace std; class Point { public: Point(doublex, double y) : x(x), y(y) { } double area() const { return 0.0; } private: double x, y; }; class Rectangle: public Point { public: Rectangle(doublex, double y, double w, double h); double area() const { return w * h; } private: double w, h; }; Rectangle::Rectangle(doublex, double y, double w, double h) :Point(x, y), w(w), h(h) { } void fun(constPoint s) { cout Area = s.area() endl; } intmain() { Rectangle rec(3.0, 5.2, 15.0, 25.0); fun(rec); return 0; } 运行结果: Area = 0 动态绑定例 #includeiostream using namespace std; class Point { public: Point(doublex, double y) : x(x), y(y) { } virtual double area() const { return 0.0; } private: double x, y; }; class Rectangle:publicPoint { public: Rectangle(doublex, double y, double w, double h); virtual double area() const { return w * h; } private: double w, h; }; //其他函数同上例 void fun(constPoint s) { cout Area = s.area() endl; } intmain() { Rectangle rec(3.0, 5.2, 15.0, 25.0); fun(rec); return 0; } 运行结果: Area =

文档评论(0)

1亿VIP精品文档

相关文档