(精)c++第8章.pptVIP

  • 9
  • 0
  • 约9.58千字
  • 约 53页
  • 2017-01-06 发布于北京
  • 举报
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * 静态绑定与动态绑定 绑定 程序自身彼此关联的过程,确定程序中的操作调用与执行该操作的代码间的关系。 静态绑定 绑定过程出现在编译阶段,用对象名或者类名来限定要调用的函数。 动态绑定 绑定过程工作在程序运行时执行,在程序运行时才确定将要调用的函数。 #includeiostream using namespace std; class Point { public: Point(double i, double j) {x=i; y=j;} double Area() const{ return 0.0;} private: double x, y; }; class Rectangle:public Point { public: Rectangle(double i, double j, double k, double l); double Area() const {return w*h;} private: double w,h; }; 静态绑定例 * Rectangle::Rectangle(double i, double j, double k, double l) :Point(i,j) { w=k; h=l; } void fun(Point s) { coutArea=s.Area()endl; } int main() { Rectangle rec(3.0, 5.2, 15.0, 25.0); fun(rec); } 运行结果: Area=0 * #includeiostream using namespace std; class Point { public: Point(double i, double j) {x=i; y=j;} virtual double Area() const{ return 0.0;} private: double x, y; }; class Rectangle:public Point { public: Rectangle(double i, double j, double k, double l); virtual double Area() const {return w*h;} private: double w,h; }; //其他函数同上例 动态绑定例 * void fun(Point s) { coutArea=s.Area()endl; } int main() { Rectangle rec(3.0, 5.2, 15.0, 25.0); fun(rec); } 运行结果: Area=375 * * 虚函数 虚函数是动态绑定的基础。 是非静态的成员函数。 在类的声明中,在函数原型之前写virtual。 virtual 只用来说明类声明中的原型,不能用在函数实现时。 具有继承性,基类中声明了虚函数,派生类中无论是否说明,同原型函数都自动为虚函数。 本质:不是重载声明而是覆盖。 调用方式:通过基类指针或引用,执行时会 根据指针指向的对象的类,决定调用哪个函数。 虚 函 数 * 例 8-4 #include iostream using namespace std; class B0 //基类B0声明 {public: //外部接口 virtual void display() //虚成员函数 {coutB0::display()endl;} }; class B1: public B0 //公有派生 { public: void display() { coutB1::display()endl; } }; class D1: public B1 //公有派生 { public: void display() { coutD1::display()endl; } }; 虚 函 数 void fun(B0 *ptr) //普通函数 { ptr-display(); } int main() //主函数 { B0 b0, *p; //声明基类对象和指针 B1 b1; //声明派生类对象 D1 d1; //声明派生类对象 p=b0; fun(p); //调用基类B0函数成员 p=b1; fun(p); //调用派生类B1函数成员 p=d1; fun(p); //调用派生类D1函数成员 } 运行结果: B0::disp

文档评论(0)

1亿VIP精品文档

相关文档