cdsfiui 发表于 2016-09-12 10:43

一个初始化列表的编译错误,帮我看下哈!


struct base{
virtual void f()=0;
int x;
};
struct derived:base{
void f(){}
int y;
derived():x(3),y(4){}
};
int main(int argc, char*argv[])
{
derived d;
return 0;
}

编译错误是:

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

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

MMMIX 发表于 2016-09-12 11:17

这问题你应该发到 C/C++ 版呀

EricFisher 发表于 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/

改成: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.

cdsfiui 发表于 2016-09-12 16:18

回复 3# EricFisher

Eric Fisher的这个答案果然是精湛!
页: [1]
查看完整版本: 一个初始化列表的编译错误,帮我看下哈!