需要解释为什么在定义类时使用一个冒号

Need an explanation on why is one colon used when defining classes

本文关键字:一个 为什么 解释 定义      更新时间:2023-10-16

我试图理解为什么下面的代码在子类后面使用一个冒号。我试着在网上搜索,但没有得到任何关于其原因的信息。

myLabel.h文件

    #ifndef MYLABEL_H
    #define MYLABEL_H
    #include <QApplication>
    #include <QMainWindow>
    #include <QHBoxLayout>
    #include <QLabel>
    #include <QMouseEvent>

    class MyLabel : public QLabel
    {
        Q_OBJECT
    public:
        explicit MyLabel(QWidget *parent = 0);
        ~MyLabel(){}
    protected:
        void mouseMoveEvent ( QMouseEvent * event );
    };
    #endif // MYLABEL_H

myLabel.cpp文件

    #include "mylabel.h"
    #include "ui_mainwindow.h"
    MyLabel::MyLabel(QWidget *parent) : QLabel(parent) //QWidget calls the widget, QLabel calls text
    {
          this->setAlignment(Qt::AlignCenter);
          //Default Label Value
          this->setText("No Value");
          //set MouseTracking true to capture mouse event even its key is not pressed
          this->setMouseTracking(true);
    }

main.cpp

//#include "mainwindow.h"
#include "mylabel.h"
#include "rectangle.h"
#include <QApplication>
#include <QHBoxLayout>
#include <QPainterPath>
           int main(int argc, char *argv[])
            {
                QApplication app(argc, argv);
                QMainWindow *window = new QMainWindow();
                    window->setWindowTitle(QString::fromUtf8("QT - Capture Mouse Move"));
                    window->resize(500, 450);
                    QWidget *centralWidget = new QWidget(window);
                QHBoxLayout* layout = new QHBoxLayout(centralWidget);
                    MyLabel* CoordinateLabel = new MyLabel();
                layout->addWidget(CoordinateLabel);
                window->setCentralWidget(centralWidget);
                window->show();
                return app.exec();
            }

    void MyLabel::mouseMoveEvent( QMouseEvent * event )
    {
        // Show x and y coordinate values of mouse cursor here
        QString txt = QString("X:%1 -- Y:%2").arg(event->x()).arg(event->y());
        setText(txt);
    }

另外,有人能解释一下myLabel.cpp文件中的指针"this"指的是什么吗?

感谢所有

这个表示继承:MyLabel类派生自QLabel类(使用公共继承,您可以在这里阅读更多):

class MyLabel : public QLabel
    {

这个调用了一个特定的基类构造函数,其思想是将MyLabel的父小部件正确地设置为parent,并且由于QLabel将指向父小部件的指针作为它的构造函数参数,所以这个构造函数被调用(此处有更多信息):

MyLabel::MyLabel(QWidget *parent) : QLabel(parent)

在您的情况下使用this是不必要的。成员函数内部的this指针指向运行该函数的对象。

相关文章: