1.将qt项目中每个文件中的每行代码注释一遍
//工程文件
QT += core gui #所需的类库
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets #超过4版本的要加widget
CONFIG += c++11 #支持c++11
# The following define makes your compiler emit warnings if you use
# any Qt feature that has been marked deprecated (the exact warnings
# depend on your compiler). Please consult the documentation of the
# deprecated API in order to know how to port your code away from it.
DEFINES += QT_DEPRECATED_WARNINGS
# You can also make your code fail to compile if it uses deprecated APIs.
# In order to do so, uncomment the following line.
# You can also select to disable deprecated APIs only up to a certain version of Qt.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0
SOURCES += \ #源文件
main.cpp \
mywindow.cpp
HEADERS += \ #头文件
mywindow.h
FORMS += \ #ui文件
mywindow.ui
# Default rules for deployment.
qnx: target.path = /tmp/$${TARGET}/bin
else: unix:!android: target.path = /opt/$${TARGET}/bin
!isEmpty(target.path): INSTALLS += target
//头文件
#ifndef MYWINDOW_H
#define MYWINDOW_H
#include <QWidget> //引入QWidget头文件
QT_BEGIN_NAMESPACE
namespace Ui { class mywindow; } //声明命名空间Ui
QT_END_NAMESPACE
class mywindow : public QWidget //mywindow类继承于Qwidget类
{
Q_OBJECT //信号与槽对应的元
public:
mywindow(QWidget *parent = nullptr); //构造函数的声明,参数是父类QWidget的指针
~mywindow(); //析构函数的声明
private:
Ui::mywindow *ui; //mywindow类的指针,用来操作ui界面上可以拖拽的组件
};
#endif // MYWINDOW_H
//源文件
#include "mywindow.h" //引入该工程下的mywindow头文件
#include "ui_mywindow.h" //引入ui文件生成的c++文件
mywindow::mywindow(QWidget *parent) //定义mywindow类的构造函数
: QWidget(parent) //调用父类QWidget的有参构造初始化继承来的成员
, ui(new Ui::mywindow) //给ui指针在堆区申请空间
{
ui->setupUi(this); //调用成员函数
}
mywindow::~mywindow() //定义mywindow类的析构函数
{
delete ui; //释放ui指针的空间
}
//测试文件
#include "mywindow.h" //引入该工程下的mywindow头文件
#include <QApplication> //引入应用程序文件
int main(int argc, char *argv[])
{
QApplication a(argc, argv); //实例化应用程序对象
mywindow w; //用mywindow类在栈区实例化对象,调用无参构造
w.show(); //调用show函数
return a.exec(); //轮询等待处理
}
2.手动实现对象树模型
#include <iostream>
#include<list> //引入链表模板库
using namespace std;
class Object
{
public:
list<Object *> child; //创建子组件链表
Object(Object *parent=nullptr) //构造函数,参数为该类的指针
{
if(parent!=nullptr)
{
//说明创建对象时,给定了父组件,要将自己的地址放到父组件的孩子链表中
parent->child.push_back(this);
}
}
virtual ~Object() //虚析构函数
{
//释放子组件链表中的所有内容
for(auto p=child.begin();p!=child.end();p++)
{
delete *p;
}
}
};
class A:public Object
{
public:
A(Object *parent=nullptr) //A构造函数,参数为父类的指针
{
if(parent!=nullptr)
{
//将A的this指针放入到父类Object创建的子组件链表中
parent->child.push_back(this);
}
cout<<"A的构造"<<endl;
}
virtual ~A() //A析构函数
{
cout<<"A的析构"<<endl;
}
};
class B:public Object
{
public:
B(Object *parent=nullptr) //B构造函数,参数为父类的指针
{
if(parent!=nullptr)
{
//将B的this指针放入到父类Object创建的子组件链表中
parent->child.push_back(this);
}
cout<<"B的构造"<<endl;
}
virtual ~B() //B析构函数
{
cout<<"B的析构"<<endl;
}
};
int main()
{
A w; //用子类A在栈区实例化对象
B *btn=new B(&w); //用子类B在堆区实例化对象
return 0;
}