non-virtual函数的调用
来源:互联网 发布:淘宝男装店铺描述 编辑:程序博客网 时间:2024/06/16 12:36
先看下面一段代码,派生类没有重新实现non-virtual函数print函数:
- #include <iostream>
- using namespace std;
- class Base
- {
- public:
- void print()
- {
- cout <<" invoked from Base" << endl;
- }
- };
-
- class Derived: public Base
- {
- public:
- //void print()//隐藏了Base::printf函数
- //{
- // cout <<" invoked from Derived" << endl;
- //}
- };
-
- int main()
- {
- Derived d;
- Base *base = &d;
- Derived *derived = &d;
- base->print();
- derived->print();
- }
运行结果:
这个结果很明显,在此不做解释。
但是如果派生类又定义了自己的函数print版本:
- #include <iostream>
- using namespace std;
- class Base
- {
- public:
- void print()
- {
- cout <<" invoked from Base" << endl;
- }
- };
-
- class Derived: public Base
- {
- public:
- void print()//隐藏了Base::printf函数
- {
- cout <<" invoked from Derived" << endl;
- }
- };
-
- int main()
- {
- Derived d;
- Base *base = &d;
- Derived *derived = &d;
- base->print();
- derived->print();
- }
输出结果:
虽然两个指针都是通过对象d来调用成员函数print,但是结果却不一样。子类Derived有自己的实现版本,隐藏了父类的print函数。
为什么这种情况下会结果不一样呢?
这是因为non-virtual函数都是静态绑定。由于base被声明为一个pointer-to-Base,通过base调用的non-virtual函数永远是Base所定义的版本。即使base指向一个类型为Base派生之Derived的对象。
更多讨论请看:http://www.dewen.org/q/5477
- non-virtual函数的调用
- C++细节学习之non-virtual、virtual和pure virtual函数的使用区别
- 绝不重新定义继承而来的non-virtual函数
- 在类的非virtual函数中调用virtual函数
- pure virtual、impure virtual 、non-virtual函数-读书笔记
- 7.1 virtual模块的函数调用关系
- virtual函数调用例题
- non-virtual和virtual
- 条款36:绝对不要重新定义继承而来的non-virtual函数
- 条款36:决不重新定义继承而来的non-virtual函数
- 条款36:绝对不要重新定义继承而来的non-virtual函数
- 条款36:绝不重新定义继承而来的non-virtual函数
- 条款36-37绝不重新定义继承而来的non-virtual函数与缺省参数
- 《Effective C++》读书笔记之item36:绝不重新定义继承而来的non-virtual函数
- 条款36:绝不重定义继承而来的non-virtual函数
- item36: 绝不重新定义继承而来的non-virtual函数
- Effective C++:条款36:绝不重新定义继承而来的non-virtual函数
- Effective C++ Item 36 绝不重新定义继承而来的 non-virtual 函数
- 超级炫的JS效果,不信你试试?
- stdafx.cpp用处
- setOnTouchListener onTouchEvent setOnClickListener
- SQL 总结
- hdu1166 敌兵布阵
- non-virtual函数的调用
- CSS 之 Position 及只用CSS做到完全居中
- Java如何读取配置文件
- 2012年北京师范大学新生程序设计竞赛网络赛
- 证书链(The Certificate Chains)
- C++中二维数组的问题
- 状态栏的一些功能实现
- C语言中的格式占位符有哪些?
- 意想不到的有趣linux命令