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

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

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

示例

#include <iostream>
#include <string>
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 <iostream>
#include <string>
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();
}

结果

最新文章

  1. javaweb局部刷新-ajax异步请求springMVC显示返回的jsp内容,代替iframe
  2. 【原创】(AMD)JavaScript模块化开发(dojo)
  3. python数字图像处理(16):霍夫圆和椭圆变换
  4. oracle里要查看一条sql的执行情况,有没有走到索引,怎么看?索引不能提高效率?
  5. ORM之Dapper操作Sql Server和MySql数据库
  6. 【25】考虑写出一个不抛异常的swap函数
  7. C++实现一个单例模板类
  8. JS中Date.parse方法返回NaN解决方案
  9. ASP.NET几种清除页面缓存的方法
  10. java reflection总结
  11. uva 639 Don&#39;t Get Rooked 变形N皇后问题 暴力回溯
  12. 解决winform窗体闪烁问题
  13. Vim设置Tab宽度/替换Tab为空格
  14. C 语言restrict 关键字的概念及使用例子
  15. 数据库之mysql篇(5)—— 【转载】mysql练习题
  16. 谷歌浏览器内核Cef js代码整理(二) 滚动条
  17. 排座椅(洛谷P1056)
  18. CentOS7系统64位下搭建Python3.6环境及相关细节工具部署文章收集
  19. 编写 T4 文本模板
  20. Redis使用示例及在PHP环境中用redis存储session

热门文章

  1. [python] [转]如何自动生成和安装requirements.txt依赖
  2. Wait--查看等待
  3. map的回调函数
  4. Spring Boot专题背景简介
  5. leetcode 加一
  6. windows部署PHP开发的cms系统
  7. 编写高质量JS代码上
  8. SPOJ distinct subtrings
  9. 在eclipse上的hdfs的文件操作
  10. [Maven实战-许晓斌]-[第三章] Mave使用入门