没考虑很多,一没经验二没时间
比较粗糙,自己这里用估计够用
当成QLabel
struct A
{
int x;
A(int x):x(x){}
void setX(int x){this->x = x;}
int getX(){return x;}
};
结构体
struct danmuLb{
A *x;
danmuLb *next;
danmuLb(A &X):
x(&X),
next(nullptr)
{
// cout<<"danmuLb constructed"<<endl;
}
~danmuLb() {
delete x;
// cout<<"--------------------------------"<<this<<endl;
// cout<<"danmuLb destroyed"<<endl;
// cout<<"----------------------------------------"<<endl;
}
void print(){
// cout<<"<--->"<<endl;
cout<<"num of this is "<<x->x<<endl;
// cout<<"addr of this: "<<this<<endl<<endl;
}
};
模板类MyQueue
//不算容器
//目前这样用着更爽
template <typename T> class MyQueue
{
private:
T *head;
T *tail;
public:
MyQueue():
head(nullptr),
tail(nullptr)
{};
~MyQueue(){
clear();
};
void push(T &x) {
if(tail != nullptr) tail->next = &x;
else head = &x;
tail = &x;
// cout<<"MyQueue pushed"<<endl;
// cout<<"head: "<<head<<" tail: "<<tail<<endl;
};
void pop() {
T *tmp = head;
head = head->next;
delete tmp;
};
T& front() {return *head;}
T& back() {return *tail;}
void clear(){
while(head != nullptr){
T *tmp = head;
head = head->next;
tmp->~T();
// delete tmp;
// 直接delete居然不调用析构函数,待解决
// 目前思路是模板类内delete不会调用析构函数
}
head = tail = nullptr;
// cout<<"MyQueue cleared"<<endl;
};
};
main函数
int main(){
MyQueue<danmuLb> danmuLbQueue;
danmuLb *tmpLb;
A *tmpA;
for(int i = 0; i < 3; i++){
tmpA = new A(0);
tmpA->setX(i);
tmpLb = new danmuLb(*tmpA);
danmuLbQueue.push(*tmpLb);
}
danmuLb tmp = danmuLbQueue.front();
cout<<"tmp: "<<&tmp<<" "<<"front(): "<<&danmuLbQueue.front()<<endl;
tmp.print();
tmp = *tmp.next;
tmp.print();
tmp = danmuLbQueue.back();
tmp.print();
delete &tmp;
cnm(123);
// tmp = *(&danmuLbQueue.back());
// 注意用引用接收引用,才能对实际属性产生影响;
danmuLb &tmp2 = danmuLbQueue.back();
cout<<"tmp2: "<<&tmp2<<" "<<"back(): "<<&danmuLbQueue.back()<<endl;
return 0;
}
附上输出:
一些其他的东西
看看它的输出
遗留问题:
- 变量的回收过程: 就算delete了变量的指针, 程序结束时还会析构一次.
- 模板中delete模板参数类的指针似乎不会调用析构函数