#include <iostream>
#include <list>
using namespace std;
class Object;
typedef list<Object*> ObjectList; //定义父组件中 子组件的链表类型
class Object
{
public:
ObjectList children; // 记录子组件的指针链表
Object(Object* parent = nullptr)//父组件类型??
{
if(parent != nullptr)
{
parent->children.push_back(this);//有父组件
}
}
virtual ~Object()
{
for(auto it=children.begin();it!=children.end(); it++)
{
delete *it;
}
}
ObjectList &childrenList()
{
return this->children;
}
};
class A:public Object
{
public:
A(Object* parent = nullptr)
{
if(parent != nullptr)
{
parent->children.push_back(this);
}
cout<<"A:构造函数"<<endl;
}
~A(){cout<<"A:析构函数"<<endl;}
};
class B:public Object
{
public:
B(Object* parent = nullptr)
{
if(parent != nullptr)
{
parent->children.push_back(this);
}
cout<<"B:构造函数"<<endl;
}
~B(){cout<<"B:析构函数"<<endl;}
};
int main()
{
A aa;
B* p = new B(&aa);
cout << "Hello World!" << endl;
return 0;
}
测试结果:
这里不太明白: Object(Object* parent = nullptr)//父组件类型??