C++语法问题,有点不太明白
阿神
阿神 2017-04-17 13:06:58
0
9
639

各位大神,有个不太明白的C++语法 :

Widget::Widget(QWidget *parent)
    : QWidget(parent)
{



}

这语法里面 函数参数后面 : QWidget(parent) 是什么意思呢 不太明白了?

阿神
阿神

闭关修行中......

reply all(9)
洪涛

Initialization of base class constructor.

洪涛

This is calling the constructor of the base class QWidget, parent is the parameter passed into the base class constructor

Peter_Zhu

Defining constructors outside the class and base class constructors

巴扎黑

Initialization list, display calling the parent class constructor in the initialization list

PHPzhong

Basic syntax of c++, initialization list.

迷茫

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)
  {
  }
  
  
左手右手慢动作

Call the constructor of the parent class. This is written on C++ Primer

PHPzhong

Constructor initialization list, the first column can use the constructor of the parent class.

Ty80

is to call the constructor of the parent class.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template