多态 中国地质大学培训教案.pptVIP

  • 4
  • 0
  • 约 35页
  • 2017-02-08 发布于江苏
  • 举报
多 态 多态是一种运行期绑定机制,通过这种机制,实现将函数名绑定到函数具体实现代码的目的。 一个函数在内存当中起始的地址就称为这个函数的入口地址。 多态就是将函数名称动态地绑定到函数入口地址的运行期绑定机制。 5.1 C++中的运行期绑定与编译期绑定 一个函数的名称与其入口地址是紧密相连的 ,入口地址是函数在内存当中的起始地址。 #include iostream using namespace std; void sayHi(); int main() { sayHi(); return 0; } void sayHi() { cout“Hello, wonderful world!”endl; } 编译期绑定是函数需要执行的代码由编译器在编译阶段确定了的。也就是说将某个函数名和其入口地址进行绑定在一起。 运行期绑定是直到程序运行之时(不是在编译时刻),才将函数名称绑定到其入口地址。 如果对一个函数的绑定发生在运行时刻而非编译时刻,我们就称该函数是多态的。 5.1.1 C++多态的前提条件 必须存在一个继承体系结构。 继承体系结构中的一些类必须具有同名的virtual成员函数(virtual是关键字) 至少有一个基类类型的指针或基类类型的引用。这个指针或引用可用来对virtual成员函数进行调用。 例子: #include iostream using namespace std; class TradesPerson { public: virtual void sayHi() { coutJust hi.endl; } }; class Tinker : public TradesPerson { public: virtual void sayHi() { coutHi, I tinker.endl; } }; class Tailor : public TradesPerson { public: virtual void sayHi() { coutHi, I tailor.endl; } }; int main() { TradesPerson* p; int which; do { cout1 == TradesPerson, 2 == Tinker, 3 == Tailor; cinwhich; } while (which 1 || which 3); switch (which) { case 1 : p = new TradesPerson; break; case 2 : p = new Tinker; break; case 3 : p = new Tailor; break; } p-sayHi(); delete p; return 0; } 注意: 基类类型的指针可以指向任何基类对象或派生类对象,反过来派生类类型的指针是不可以的基类的对象的。 例: #include iostream #include cstdlib #include ctime using namespace std; class TradesPerson { public: virtual void sayHi() {coutJust hi.endl;} }; class Tinker : public TradesPerson { public: virtual void sayHi() {coutHi, I tinker.endl;} }; class Tailor : public TradesPerson { public: virtual void sayHi() {coutHi, I tailor.endl;} }; int main() { srand( (unsigned) time( NULL ) ); int i = 0; TradesPerson* ptrs[10]; for (i=0; i10; i++) { which = 1 + rand() % 3; switch (which) { case 1 : p = new TradesPerson; break; case 2 : p = new Tinker; break; case 3 : p = new Tailor; break; } } for (i=0; i10;

您可能关注的文档

文档评论(0)

1亿VIP精品文档

相关文档