首页 > 学院 > 开发设计 > 正文

13.2.2

2019-11-11 07:44:57
字体:
来源:转载
供稿:网友

13.27

#include<string>using std::string;class Hasptr {public: HasPtr(const string& s = string()):ps(new string(s)),i(0),use(new size_t(1)) {} HasPtr(const HasPtr& p) :ps(p.ps), i(p.i), use(p.use) { ++use; } HasPtr& Operator=(const HasPtr&); ~HasPtr();PRivate: string* ps; int i; std::size_t* use;};HasPtr::~HasPtr() { if (--*use == 0) { delete ps; delete use; }}HasPtr& HasPtr::operator=(const HasPtr& rhs) { ++*rhs.use; if (--*use == 0) { delete ps; delete use; } ps = rhs.ps; use = rhs.use; i = rhs.i; return *this;}

13.28

#include <string>using std::string;class TreeNode {public: TreeNode() : value(string()), count(new int(1)), left(nullptr), right(nullptr) { } TreeNode(const TreeNode &rhs) : value(rhs.value), count(rhs.count), left(rhs.left), right(rhs.right) { ++*count; } TreeNode& operator=(const TreeNode &rhs); ~TreeNode() { if (--*count == 0) { delete left; delete right; delete count; } }private: std::string value; int *count; TreeNode *left; TreeNode *right;};class BinStrTree {public: BinStrTree() : root(new TreeNode()) { } BinStrTree(const BinStrTree &bst) : root(new TreeNode(*bst.root)) { } BinStrTree& operator=(const BinStrTree &bst); ~BinStrTree() { delete root; }private: TreeNode *root;};TreeNode& TreeNode::operator=(const TreeNode &rhs){ ++*rhs.count; if (--*count == 0) { delete left; delete right; delete count; } value = rhs.value; left = rhs.left; right = rhs.right; count = rhs.count; return *this;}BinStrTree& BinStrTree::operator=(const BinStrTree &bst){ TreeNode *new_root = new TreeNode(*bst.root); delete root; root = new_root; return *this;}
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表