Qt中实例化一个函数变量时加不加括号的区别,以及括号中的this的使用

30 篇文章 4 订阅

一、设计一个测试小程序

废话不多说,直接上代码。
main.h函数就不多说了,没改动。直接上mainwindow.h,也没改动。看mainwindow.cpp的内容。

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "test.h"
#include <QDebug>
MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    test *mtest=new test(this,3);
    test *mtest2=new test();
    test *mtest3=new test;

    int *mvalue1=new int();
    int *mvalue2=new int;

    qDebug()<<mtest;
    qDebug()<<mtest2;
    qDebug()<<mtest3;

    qDebug()<<mvalue1;
    qDebug()<<mvalue2;
    qDebug()<<*mvalue1;
    qDebug()<<*mvalue2;
}

MainWindow::~MainWindow()
{
    delete ui;
}


看看test.h的内容

#ifndef TEST_H
#define TEST_H

#include <QDebug>
#include <QLabel>
#include <QWidget>

class test: public QWidget
{
public:
    test(QWidget *parent = nullptr, int num=4));

};

#endif // TEST_H

test.cpp的内容。

#include "test.h"

test::test(QWidget *parent,int num) :
    QWidget(parent)
{
    QWidget* pWidget = this->parentWidget();
    if(pWidget)
    {
        pWidget->findChild<QLabel*>("label")->setText("init test class");
    }
    qDebug()<<"init test class";
    qDebug()<<num;
}

运行后,打印输出的内容为:

init test class
3
init test class
4
init test class
4
QWidget(0x12e1c6b10)
QWidget(0x12e1c6820)
QWidget(0x12e1c64e0)
0x12e093360
0x12e1c6b70
0
773385776

先是的图形界面为:
在这里插入图片描述
由此可以得出后续结论。

二、加不加括号的区别

  1. 加或不加括号都会进行初始化,并且运行构造函数。
  2. 加或不加括号,都在内存中开辟出了空间,确定了该类的位置。
  3. 只是当new的是一个int之类的数据类型,这个情况就会不太一样,加括号时,会将基础类型赋值为0,不加括号时,则是一个随机值。

三、括号中加this的含义

其实传递this,与传递别的参数没有区别,同个道理,就是在创建一个函数变量的实例时,其构造函数中的括号内有与this相同的参数类型,则可以传递this进到这个新创建的实例中去。
即该函数类的构造函数需要有一个QWidget的参数,则此时就可以在new该函数变量时,添加(this),来传递this的界面类。
至于括号中为空的解释,一般在一个类在构造函数中定义传递的参数时,都会设置一个初始的默认值,比如QWidget *parent = nullptr,因此当有默认值时,括号中则可以为空,括号为空,则自定初始化为默认值,即nullptr。

  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

鱼月半

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值