这是正确的方式,boost::shared_ptr
用于节点左右和boost::weak_ptr
根。我知道共享是一种矫枉过正。我以后需要这个。
类节点,2个儿子共享ptr
class Node
{
public:
boost::shared_ptr<Node> left;
boost::shared_ptr<Node> rigth;
int nVal;
Node();
Node(int);
~Node();
Node getVal(void);
void setVal(int);
};
Node::Node()
{
cout << "creating node empty" << endl;
nVal = 0;
left.reset();
rigth.reset();
}
Node::~Node()
{
cout << "entering destructor" << endl;
}
Node::Node(int n)
{
cout << "creating node with value" << endl;
nVal = n;
left.reset();
rigth.reset();
}
Node Node::getVal(void)
{
cout << "returning value" << endl;
return this;
}
void Node::setVal(int n)
{
cout << "setting value" << endl;
nVal = n;
}
类树,弱指针
class Tree
{
public:
boost::weak_ptr<Node> root;
Tree();
~Tree();
void findParent(int n, int &found, Node &parent);
void add(int n);
void post(boost::weak_ptr<Node> q);
void del(int n);
};
Tree::Tree()
{
root = NULL;
}