各位大神,有个不太明白的C++语法 :
Widget::Widget(QWidget *parent)
: QWidget(parent)
{
}
这语法里面 函数参数后面 : QWidget(parent) 是什么意思呢 不太明白了?
PHP中文网2017-04-17 13:08:58
This is calling the constructor of the base class QWidget, parent is the parameter passed into the base class constructor
巴扎黑2017-04-17 13:08:58
Initialization list, display calling the parent class constructor in the initialization list
迷茫2017-04-17 13:08:58
This is the Member Initializer List. Its purpose is that when the QWidget* parent parameter is passed into the Widget's constructor, the QWidget member in the Widget class will be initialized with parent, that is, QWidget(parent).
The advantage of using member initialization list is that it can reduce copying, for example:
//假使QWidget的类型为SomeWidget
Widget::Widget(QWidget *parent) {
//QWidget = parent;//Wrong!这是一个赋值行为
QWidget = SomeWidget(parent);//Correct,但是QWidget被初始化了两次
};
This is because C++ stipulates that the initialization of member variables occurs before entering the constructor, that is, the member QWidget
will be initialized before entering the constructor. Here, it is initialized by the default constructor. Therefore, in the above code, QWidget is initialized twice by
, plus the = operator (Assign Operator) is called once. The cost of these operations is higher than using the member
initialization list. So generally speaking, try to use member initialization lists. That is:
Widget::Widget(QWidget *parent)
: QWidget(parent)
{
}
ringa_lee2017-04-17 13:08:58
Call the constructor of the parent class. This is written on C++ Primer
PHPz2017-04-17 13:08:58
Constructor initialization list, the first column can use the constructor of the parent class.