免费注册 查看新帖 |

Chinaunix

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

求助大侠 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2011-04-23 21:51 |只看该作者 |倒序浏览
  1. #include <iostream.h>

  2. class MyClass
  3. {
  4. public:
  5.         int data;
  6.         MyClass(int data)
  7.         {
  8.                 this->data=data;
  9.         }
  10.         void print()
  11.         {
  12.                 //cout<<data<<endl;
  13.                 cout<<"hello!"<<endl;
  14.         }
  15. };

  16. int main()
  17. {
  18.         MyClass *pMyClass;
  19.         pMyClass=new MyClass(1);
  20.         pMyClass->print();
  21.         pMyClass[0].print();
  22.         pMyClass[1].print();
  23.         pMyClass[10000000].print();

  24.         return 0;
  25. }
复制代码
那位大侠帮我讲一下这个在注释第13行前后的问题,这段代码我不是很理解,谢谢大家了

论坛徽章:
5
技术图书徽章
日期:2013-11-07 13:21:58技术图书徽章
日期:2013-12-07 10:34:46技术图书徽章
日期:2014-04-23 08:50:31双鱼座
日期:2014-09-16 09:12:34亥猪
日期:2015-01-23 13:37:49
2 [报告]
发表于 2011-04-23 22:19 |只看该作者
对于非virtual编译器实际的处理为:
MyClass_print (MyClass *this),这和c中的函数没啥区别,只是限定了只能 MyClass这个类使用而已。
编译器会吧 print的调用转为 MyClass_print(MyClass *this)的形式
对于 pMyClass[1] pMyClass[1000],this的值就超出范围了。但是没有访问任何数据成员所以没问题。

ps==========================
你在 print定义时加个 virtual 看看,就挂了把。
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

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

清除 Cookies - ChinaUnix - Archiver - WAP - TOP