抽象类 作用 抽象类为抽象和设计的目的而声明,将有关的数据和行为组织在一个继承层次结构中,保证派生类具有要求的行为。 对于暂时无法实现的函数,可以声明为纯虚函数,留给派生类去实现。 注意 抽象类只能作为基类来使用。 不能声明抽象类的对象。 构造函数不能是虚函数,析构函数可以是虚函数。 例如 #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 =
您可能关注的文档
最近下载
- 8173wst5542017学生餐营养指南.pdf VIP
- 器械相关感染的防控课件.pptx VIP
- 保教知识与能力(幼儿园)全套PPT课件.pptx
- 手术室流程优化.pptx VIP
- 2025年度组织生活会个人对照检查材料(党员个人).doc VIP
- 《十万个为什么》阅读测试题(附答案)(推荐).docx VIP
- 2026年教师师德师风培训学习心得体会.docx
- 《餐饮服务》课程知识解析——“18.西餐服务流程与标准(英法美等不同服务方式)”.pdf VIP
- 建设项目工程结算编审规程,CECA_GC3-2010.pdf VIP
- 党员干部个人组织生活会个人对照(学习贯彻党的创新理论方面;加强党性锤炼方面;联系服务职工群众方面;发挥先锋模范作用方面;改作风树新风等方面)存在的问题清单及整改措施.docx VIP
原创力文档

文档评论(0)