免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 2151 | 回复: 1
打印 上一主题 下一主题

[C++] C++派生类赋值兼容原则,实际出现的结果与视频上老师讲的不同 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2012-11-07 20:51 |显示全部楼层 |倒序浏览
  1. #include <iostream>
  2. using namespace std;

  3. class B0{
  4. public:
  5.     void display(){
  6.         cout<<"B0:display()"<<endl;
  7.     }
  8. };
  9. class B1:public B0{
  10. public:
  11.     void display(){
  12.         cout<<"B1::display()"<<endl;
  13.     }
  14. };
  15. class D1:public B1{
  16. public:
  17.     void display(){
  18.         cout<<"D1::display()"<<endl;
  19.     }
  20. };
  21. void fun(B0 *ptr){
  22.     ptr->display();
  23. }
  24. int main(){
  25.     B0 b0;
  26.     B1 b1;
  27.     D1 d1;
  28.     B0 *p;
  29.     p=&b0;
  30.     cout<<"b0"<<p<<endl;
  31.     fun(p);
  32.     p=&b1;
  33.     cout<<"b1"<<p<<endl;
  34.     fun(p);
  35.     p=&d1;
  36.     cout<<"d1"<<p<<endl;
  37.     fun(p);
  38. }
复制代码
实际结果是出现3个B0:display():

B0:display()
B0:display()
B0:display()

老师讲的应该出现

B0:display()
B1:display()
D1:display()


请问如何解决?

论坛徽章:
0
2 [报告]
发表于 2012-11-07 21:07 |显示全部楼层
folklore 发表于 2012-11-07 21:01
virtual在哪里,帮我找找噬,Thinks

谢谢老兄


您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP