c++构造函数问题
#include <QApplication>
#include <QFont>
#include <QPushButton>
#include <QWidget>
class MyWidget : public QWidget
{
public:
MyWidget(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();
}
对于这一行:MyWidget(QWidget *parent = 0);
为什么我们需要在这里放置 = 0
?
#include <QApplication>
#include <QFont>
#include <QPushButton>
#include <QWidget>
class MyWidget : public QWidget
{
public:
MyWidget(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??
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
它称为默认参数
基本上你是说,除非你传递另一个值,否则函数(或本例中的构造函数)将被调用,父级为 0。
当你将
MyWidget(QWidget *parent);
作为构造函数时,您必须像MyWidget widget(0);
那样调用它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 likeMyWidget widget(0);
您不必在那里输入零。 C++ 允许您为参数设置默认值。在这种情况下,如果调用构造函数时未指定参数,则参数
parent
将默认为 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.不需要把它放在那里,但它是默认值。如果您不向构造函数传递任何值,它将采用“0”作为值。在某些情况下,它使程序员的事情变得更容易一些。
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.