【c++】动态绑定
2024-08-28 09:21:22
C++的函数调用默认不使用动态绑定。要触发动态绑定,必须满足两个条件:
- 只有指定为虚函数的成员函数才能进行动态绑定
- 必须通过基类类型的引用或指针进行函数调用
因为每个派生类对象中都拥有基类部分,所以可以使用基类类型的指针或引用来引用派生类对象
示例
#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();
}
结果
最新文章
- javaweb局部刷新-ajax异步请求springMVC显示返回的jsp内容,代替iframe
- 【原创】(AMD)JavaScript模块化开发(dojo)
- python数字图像处理(16):霍夫圆和椭圆变换
- oracle里要查看一条sql的执行情况,有没有走到索引,怎么看?索引不能提高效率?
- ORM之Dapper操作Sql Server和MySql数据库
- 【25】考虑写出一个不抛异常的swap函数
- C++实现一个单例模板类
- JS中Date.parse方法返回NaN解决方案
- ASP.NET几种清除页面缓存的方法
- java reflection总结
- uva 639 Don&#39;t Get Rooked 变形N皇后问题 暴力回溯
- 解决winform窗体闪烁问题
- Vim设置Tab宽度/替换Tab为空格
- C 语言restrict 关键字的概念及使用例子
- 数据库之mysql篇(5)—— 【转载】mysql练习题
- 谷歌浏览器内核Cef js代码整理(二) 滚动条
- 排座椅(洛谷P1056)
- CentOS7系统64位下搭建Python3.6环境及相关细节工具部署文章收集
- 编写 T4 文本模板
- Redis使用示例及在PHP环境中用redis存储session