0


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

一、设计一个测试小程序

废话不多说,直接上代码。
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=newtest(this,3);
    test *mtest2=newtest();
    test *mtest3=new test;int*mvalue1=newint();int*mvalue2=newint;qDebug()<<mtest;qDebug()<<mtest2;qDebug()<<mtest3;qDebug()<<mvalue1;qDebug()<<mvalue2;qDebug()<<*mvalue1;qDebug()<<*mvalue2;}MainWindow::~MainWindow(){delete ui;}

看看test.h的内容

#ifndefTEST_H#defineTEST_H#include<QDebug>#include<QLabel>#include<QWidget>classtest:publicQWidget{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
0773385776

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

二、加不加括号的区别

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

三、括号中加this的含义

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

QWidget *parent = nullptr

,因此当有默认值时,括号中则可以为空,括号为空,则自定初始化为默认值,即nullptr。

标签: qt ui new

本文转载自: https://blog.csdn.net/baidu_31788709/article/details/128425226
版权归原作者 鱼月半 所有, 如有侵权,请联系我们删除。

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

还没有评论