博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
【c++】动态绑定
阅读量:6910 次
发布时间:2019-06-27

本文共 1778 字,大约阅读时间需要 5 分钟。

C++的函数调用默认不使用动态绑定。要触发动态绑定,必须满足两个条件:

  1. 只有指定为虚函数的成员函数才能进行动态绑定
  2. 必须通过基类类型的引用或指针进行函数调用

因为每个派生类对象中都拥有基类部分,所以可以使用基类类型的指针或引用来引用派生类对象

示例

#include 
#include
using namespace std;struct base{ base(string str = "Base") : basename(str) {} virtual void print() { cout << basename << endl; } private: string basename;};struct derived : public base{ derived(string str = "Derived") : derivedname(str) {} void print() { cout << derivedname << endl; } private: string derivedname;};int main(){ base b; derived d; cout << "b.print(), d.print()" << endl; b.print(); d.print(); base *pb = &b; base *pd = &d; cout << "pb->print(), pd->print()" << endl; pb->print(); pd->print(); base &yb = b; base &yd = d; cout << "yb.print(), yd.print()" << endl; yb.print(); yd.print();}

结果

 分析

可以看出基类类型的指针或引用来引用派生类对象时,调用的是重定义的虚函数。要想覆盖虚函数机制,调用基函数的版本,可以使用强制措施。例:

代码

#include 
#include
using namespace std;struct base{ base(string str = "Base") : basename(str) {} virtual void print() { cout << basename << endl; } private: string basename;};struct derived : public base{ derived(string str = "Derived") : derivedname(str) {} void print() { cout << derivedname << endl; } private: string derivedname;};int main(){ base b; derived d; cout << "b.print(), d.print()" << endl; b.print(); d.base::print(); base *pb = &b; base *pd = &d; cout << "pb->print(), pd->print()" << endl; pb->print(); pd->base::print(); base &yb = b; base &yd = d; cout << "yb.print(), yd.print()" << endl; yb.print(); yd.base::print();}

结果

本文转自jihite博客园博客,原文链接:http://www.cnblogs.com/kaituorensheng/p/3509593.html,如需转载请自行联系原作者

你可能感兴趣的文章
TeXworks代码补全功能
查看>>
java+jsp+mysql网页制作总结(1)
查看>>
获取当前操作的IFrame 对象的方法
查看>>
年月日下拉选择三级联动(闰年判断),时间获取方法总结,特殊:获取当前月天数...
查看>>
Tallest Cow(POJ3263)
查看>>
POJ—Building a Space Station
查看>>
杭电oj Problem-1013 Digital Roots
查看>>
CRM 2013 切换显示语言
查看>>
Codeforces Round #544 (Div. 3) C. Balanced Team
查看>>
UML-对象图
查看>>
【leetcode】1037. Valid Boomerang
查看>>
一起学Android之Layout
查看>>
PHP网页计时工具——SESSION问题
查看>>
PHP 真正多线程的使用
查看>>
ip黑白名单防火墙frdev的原理与实现
查看>>
ajax全接触
查看>>
ps查看内存占用排序
查看>>
【BZOJ】4873: [Shoi2017]寿司餐厅
查看>>
【CodeForces】913 D. Too Easy Problems
查看>>
二十四种设计模式:命令模式(Command Pattern)
查看>>