- 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;
您可能关注的文档
- 多媒体基础知识之图像及计算培训教案.ppt
- 多媒体技术基础及应用本培训教案.ppt
- 多元线性回归演示文件修改版.ppt
- 多媒体应用(声音)培训教案.ppt
- 多元随机变量及其分布演示文件修改版.ppt
- 多媒体产品方案调查培训教案.ppt
- 多媒体技术图像处理质量衡量标准PSNR培训教案.ppt
- 多媒体技术 培训教案.ppt
- 多媒体技术复习培训教案.ppt
- 多媒体数据压缩编码技术培训教案.ppt
- GB/T 42818.2-2026认知无障碍 第2部分:报告.pdf
- 中国国家标准 GB/T 47116-2026地下采矿机械 工作面移动式采掘机械 采煤机和犁式系统的安全要求.pdf
- 《GB/T 47116-2026地下采矿机械 工作面移动式采掘机械 采煤机和犁式系统的安全要求》.pdf
- 中国国家标准 GB/T 42818.2-2026认知无障碍 第2部分:报告.pdf
- 《GB/T 42818.2-2026认知无障碍 第2部分:报告》.pdf
- 《GB/T 27664.1-2026无损检测仪器 超声检测设备的性能与检验 第1部分:仪器》.pdf
- 中国国家标准 GB/T 27664.1-2026无损检测仪器 超声检测设备的性能与检验 第1部分:仪器.pdf
- GB/T 27664.1-2026无损检测仪器 超声检测设备的性能与检验 第1部分:仪器.pdf
- GB/T 45305.5-2026声学 建筑构件隔声的实验室测量 第5部分:测试设施和设备的要求.pdf
- 中国国家标准 GB/T 45305.5-2026声学 建筑构件隔声的实验室测量 第5部分:测试设施和设备的要求.pdf
原创力文档

文档评论(0)