需要解释为什么在定义类时使用一个冒号
Need an explanation on why is one colon used when defining classes
我试图理解为什么下面的代码在子类后面使用一个冒号。我试着在网上搜索,但没有得到任何关于其原因的信息。
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
指针指向运行该函数的对象。
相关文章:
- 为什么两个不同的未命名名称空间可以共存于一个cpp文件中
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 为什么 sscanf 无法从一个字符串中读取uint64_t和字符?
- 为什么我不能在一个类的不同行中声明和定义成员变量?
- 我不明白为什么我声明一个空的内部结构并将其传递给构造函数
- 为什么文件名被设置为一个点,而不是在读取矢量中的文件名时
- 为什么我不能将一个对象push_back到属于另一个类的对象向量中?
- 如果有一个模板构造函数只有一个泛型参数,为什么我必须有一个复制构造函数
- 为什么我必须在C++中添加一个赋值符号来声明一个数组
- 为什么一个向量上的多线程操作很慢
- 为什么需要知道一个类是平凡的还是有平凡的构造函数
- 为什么C++在将一个对象复制到另一个对象时需要对这两个对象进行低级常量限定
- 为什么我们要为avl树实现返回一个指向节点的指针,而不是void函数
- 为什么它只打印双链接列表的第一个值,而我的程序却崩溃了
- 为什么C++对链表中的下一个节点使用指针,而像 C# 或 Java 这样的语言只使用类 Node 的名称?
- 为什么这个程序返回最后一个单词而不是最长的单词?
- 为什么我的 heap.h 文件给我一个LNK2001错误?
- 为什么这个案例陈述需要一个"if else"而不仅仅是一个"if"?
- 为什么将一个结构的引用设置为等于另一个结构只会更改一个数据成员?
- 为什么 C++ std::unordered_map 从 emplace/ 找到返回一个迭代器?