开发者

c++ constructor question

#include <QApplication>
#include <QFont>
#include <QPushButton>
#include <QWidget>

class MyWidget : public QWidget
{
public:
    M开发者_高级运维yWidget(QWidget *parent = 0);
};

MyWidget::MyWidget(QWidget *parent)
    : QWidget(parent)
{
    setFixedSize(200, 120);

    QPushButton *quit = new QPushButton(tr("Quit"), this);
    quit->setGeometry(62, 40, 75, 30);
    quit->setFont(QFont("Times", 18, QFont::Bold));

    connect(quit, SIGNAL(clicked()), qApp, SLOT(quit()));
}

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    MyWidget widget;
    widget.show();
    return app.exec();
}

For this line : MyWidget(QWidget *parent = 0); why we need to put = 0 here??


It is called an Default parameter

Basically you are saying unless you pass another value, the function (or constructor in this case) will be called with parent as 0.

When you'd had MyWidget(QWidget *parent); as constructor, you'd had to call it like MyWidget widget(0);


You do not have to put zero there. C++ allows you to put default value for a parameter. In this case, parameter parent will default to 0 if the constructor is invoked without specifying an argument.


Don't need to put it there, but it's a default value. If you don't pass any value to the constructor, it will take the '0' as value. It's making things a bit easier in some cases for the programmer.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜