手动实现对象树模型
#include <iostream>
#include <list>
using namespace std;
class ObjTree
{
private:
list<ObjTree*> childlist;//存放子类对象的指针链表
public:
ObjTree(ObjTree* parent = nullptr)//无参构造,默认参数是nullptr
{
if(parent != nullptr)
{
parent->childlist.push_back(this);
}
cout << "ObjTree 的构造" << endl;
}
//析构函数
virtual ~ObjTree()
{
for(auto it = this->childlist.begin(); it != this->childlist.end(); it++)
{
delete *it;
}
cout << "ObjTree 的析构" << endl;
}
//获取链表
list<ObjTree*>& child()
{
return this->childlist;
}
};
class child1: public ObjTree
{
public:
child1(ObjTree* parent = nullptr)
{
if(parent != nullptr)
{
parent->child().push_back(this);
}
cout << "child1 的构造" << endl;
}
~child1(){ cout << "child1 的析构" << endl; }
};
class child2: public ObjTree
{
public:
child2(ObjTree* parent = nullptr)
{
if(parent != nullptr)
{
parent->child().push_back(this);
}
cout << "child2 的构造" << endl;
}
~child2(){ cout << "child2 的析构" << endl; }
};
int main()
{
child1 ch1;
child2 *ch2 = new child2(&ch1);
return 0;
}
结果:
ObjTree 的构造
child1 的构造
ObjTree 的构造
child2 的构造
child1 的析构
child2 的析构
ObjTree 的析构
ObjTree 的析构
2.创建一个项目,提供三个按钮,第一个按钮实现播报第二个按钮的内容,播报结束后,设置自己不可用。第二个按钮的内容是关闭,实现功能是关掉整个项目,第三个按钮功能是将第一个按钮设置为可以状态
.h文件
#ifndef MYWINDOW_H
#define MYWINDOW_H
#include <QPushButton>
#include <QWidget>
#include <QTextToSpeech>
class mywindow : public QWidget
{
Q_OBJECT
public slots:
void show_msg();
void enable_button();
void quit_system();
public:
mywindow(QWidget *parent = nullptr);
~mywindow();
QPushButton* button1;//播报
QPushButton* button2;//关闭
QPushButton* button3;//使能
QTextToSpeech speech;//播报者
};
#endif // MYWINDOW_H
.cpp文件:
#include "mywindow.h"
#include <QDebug>
void mywindow::show_msg()
{
speech.say(this->button2->text());
this->button1->setEnabled(false);
}
void mywindow::enable_button()
{
this->button1->setEnabled(true);
}
void mywindow::quit_system()
{
this->close();
}
mywindow::mywindow(QWidget *parent)
: QWidget(parent)
{
this->resize(800, 600);
this->setMaximumSize(1200, 900);
this->setMinimumSize(400, 300);
button1 = new QPushButton(this);
button1->resize(75,30);
button1->move(0,this->height()/2);
button1->setText("播报");
button2 = new QPushButton(this);
button2->resize(75,30);
button2->setText("关闭");
button2->move(2*button1->width(), this->height()/2);
button3 = new QPushButton(this);
button3->resize(75,30);
button3->setText("使能");
button3->move(button1->width(),this->height()/2);
connect(button1, &QPushButton::clicked, this, &mywindow::show_msg);//播报
connect(button2, &QPushButton::clicked, this, &mywindow::quit_system);//关闭
connect(button3, &QPushButton::clicked, this, &mywindow::enable_button);//使能
//larmda表达式
// connect(button1, &QPushButton::clicked, [&](){
// speech.say(this->button2->text());
// this->button1->setEnabled(false);
// });
// connect(button2, &QPushButton::clicked, [&](){ this->close(); } );
// connect(button3, &QPushButton::clicked, [&](){ this->button1->setEnabled(true); } );
}
mywindow::~mywindow()
{
}
结果: