[英]warning: derived class's member variable is initialized after base class
The title of the question is plain and simple. 问题的标题很简单。 here is the code:
这是代码:
class xxx : public Scheduled
{
long int _wait_time;
boost::function< void() > _cb;
mutable boost::mutex _mutex;
public:
xxx(boost::function< void() > callback, unsigned int wait_time = 10000000)
:_wait_time(wait_time),_cb(callback)
,Scheduled(Timer(_wait_time, 0))
{
this->stop();
}
};
and although I respect the order of initialization, here is the warning I get: 尽管我尊重初始化的顺序,但是这是我得到的警告:
---: In constructor ‘xxx::xxx(boost::function<void ()()>, unsigned int)’:
---: warning: ‘xxx::_cb’ will be initialized after
---: warning: base ‘Scheduled’
---: warning: when initialized here
Any thoughts? 有什么想法吗? thank you
谢谢
You are initializing your derived class members befor you construct the base class. 在构造基类之前,您正在初始化派生类成员。
xxx(boost::function< void() > callback, unsigned int wait_time = 10000000)
:_wait_time(wait_time),_cb(callback) <- derived class memebers
,Scheduled(Timer(_wait_time, 0)) <- Base class
{
this->stop();
}
In C++ the base class must be constructed before the members of the derived class are initialized. 在C ++中,必须在初始化派生类的成员之前构造基类。 So the warning is telling you that even though you have the base class initialization after the derived members it is going to construct the base class first.
因此,警告告诉您,即使在派生成员之后进行了基类初始化,它仍将首先构造基类。
If you change your code to 如果您将代码更改为
xxx(boost::function< void() > callback, unsigned int wait_time = 10000000)
:Scheduled(Timer(wait_time, 0))
^ use wait_time instead of _wait_time
,_wait_time(wait_time),
,_cb(callback)
{
this->stop();
}
You should no longer get a warning. 您应该不再收到警告。
The base class constructor has to be the first one in the initialization list: 基类构造函数必须是初始化列表中的第一个:
xxx(boost::function< void() > callback, unsigned int wait_time = 10000000)
:Scheduled(Timer(_wait_time, 0))
,_wait_time(wait_time),
,_cb(callback)
{
this->stop();
}
Adding to the other answers: 除其他答案外:
another reason for this warning can come about if your initialisers are in a different order than the order in which they appear in the class. 如果初始化程序的顺序与它们在类中的显示顺序不同,则可能会出现此警告。
Example: 例:
struct A { .. };
struct B { .. };
struct C
{
A a;
B b;
C(..) : a(..), b(..) {} // OK
C(..) : b(..), a(..) {} // Wreorder-warning
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.