免费注册 查看新帖 |

Chinaunix

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

一个初始化列表的编译错误,帮我看下哈! [复制链接]

论坛徽章:
2
2015年迎新春徽章
日期:2015-03-04 10:16:532015元宵节徽章
日期:2015-03-06 15:53:22
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2016-09-12 10:43 |只看该作者 |倒序浏览

  1. struct base{
  2.   virtual void f()=0;
  3.   int x;
  4. };
  5. struct derived:base{
  6.   void f(){}
  7.   int y;
  8.   derived():x(3),y(4){}
  9. };
  10. int main(int argc, char*argv[])
  11. {
  12.   derived d;
  13.   return 0;
  14. }
复制代码

编译错误是:

  1. 1.cpp: In constructor ‘derived::derived()’:
  2. 1.cpp:13:13: error: class ‘derived’ does not have any field named ‘x’
  3.    derived():x(3),y(4){}
复制代码

没觉得哪里写错了啊,到底要怎么改呢?
谢谢!

论坛徽章:
95
程序设计版块每日发帖之星
日期:2015-09-05 06:20:00程序设计版块每日发帖之星
日期:2015-09-17 06:20:00程序设计版块每日发帖之星
日期:2015-09-18 06:20:002015亚冠之阿尔艾因
日期:2015-09-18 10:35:08月度论坛发贴之星
日期:2015-09-30 22:25:002015亚冠之阿尔沙巴布
日期:2015-10-03 08:57:39程序设计版块每日发帖之星
日期:2015-10-05 06:20:00每日论坛发贴之星
日期:2015-10-05 06:20:002015年亚冠纪念徽章
日期:2015-10-06 10:06:482015亚冠之塔什干棉农
日期:2015-10-19 19:43:35程序设计版块每日发帖之星
日期:2015-10-21 06:20:00每日论坛发贴之星
日期:2015-09-14 06:20:00
2 [报告]
发表于 2016-09-12 11:17 |只看该作者
这问题你应该发到 C/C++ 版呀

论坛徽章:
2
摩羯座
日期:2013-10-10 14:29:04天蝎座
日期:2014-01-03 09:14:49
3 [报告]
发表于 2016-09-12 15:50 |只看该作者
本帖最后由 EricFisher 于 2016-09-12 15:54 编辑

参见 https://geekwentfreak-raviteja.rhcloud.com/blog/2014/08/05/c-initializing-parent-class-member-variables-in-derived-class-constructor/

改成:
  1. derived() : y(4) { x = 3; }
复制代码


原因参见 http://www.learncpp.com/cpp-tutorial/114-constructors-and-initialization-of-derived-classes/

Why does C++ do this? The answer has to do with const and reference variables. Consider what would happen if m_nValue were const. Because const variables must be initialized with a value at the time of creation, the base class constructor must set its value when the variable is created. However, when the base class constructor finishes, the derived class constructors initialization lists are then executed. Each derived class would then have the opportunity to initialize that variable, potentially changing it’s value! By restricting the initialization of variables to the constructor of the class those variables belong to, C++ ensures that all variables are initialized only once.

评分

参与人数 1信誉积分 +10 收起 理由
cdsfiui + 10 很给力!

查看全部评分

论坛徽章:
2
2015年迎新春徽章
日期:2015-03-04 10:16:532015元宵节徽章
日期:2015-03-06 15:53:22
4 [报告]
发表于 2016-09-12 16:18 |只看该作者
回复 3# EricFisher

Eric Fisher的这个答案果然是精湛!
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

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

清除 Cookies - ChinaUnix - Archiver - WAP - TOP