#include #include using namespace std; class Tree{ private: int age; vector<Tree*>children; public: Tree(int n){ age=n; cout<'Constructing a tree with age '<age<<endl; } Tree(const Tree& t){ age=t.age; children=t.children; cout<'Copying a tree with age '<age<<endl; } ~Tree(){ for(int i=0;i<children.size();i++){ delete children[i]; } cout<'Destroying a tree with age '<age<<endl; } void grow(int years){ age+=years; } void addChild(Tree* child){ children.push_back(child); } void printAge(){ cout<'Age of the tree is '<age<<endl; } };

int main(){ Tree* a=new Tree(10); a->addChild(new Tree(5)); a->addChild(new Tree(6)); a->printAge();

Tree* b=new Tree(*a);
b->printAge();

delete a;
delete b;
return 0;

}

C++ 树类拷贝构造函数和析构函数实现及对象构造和析构过程分析

原文地址: https://www.cveoy.top/t/topic/nyTf 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录