C++ //练习 13.28 给定下面的类,为其实现一个默认构造函数和必要的拷贝控制成员。

C++ Primer(第5版) 练习 13.28

练习 13.28 给定下面的类,为其实现一个默认构造函数和必要的拷贝控制成员。

cpp 复制代码
( a )
class TreeNode{
	private:
	string value;
	int count;
	TreeNode *left;
	TreeNode *right;
};
( b )
class BinStrTree{
	private:
	TreeNode *root;
};
环境:Linux Ubuntu(云服务器)
工具:vim
代码块
cpp 复制代码
( a )
class TreeNode {
private:
    std::string value;
    int count;
    TreeNode *left;
    TreeNode *right;

public:
    TreeNode(const std::string& val = std::string(), int cnt = 0): value(val), count(cnt), left(nullptr), right(nullptr) {}
    
    TreeNode(const TreeNode& other): value(other.value), count(other.count) {
        left = other.left ? new TreeNode(*other.left) : nullptr;
        right = other.right ? new TreeNode(*other.right) : nullptr;
    }
    
    ~TreeNode() {
        delete left;
        delete right;
    }
    
    TreeNode& operator=(const TreeNode& other) {
        if (this != &other) {
            TreeNode tmp(other);
            std::swap(value, tmp.value);
            std::swap(count, tmp.count);
            std::swap(left, tmp.left);
            std::swap(right, tmp.right);
        }
        return *this;
    }
};

( b )
class BinStrTree {
private:
    TreeNode *root;

public:
    BinStrTree() : root(nullptr) {}
    
    BinStrTree(const BinStrTree& other) {
        root = other.root ? new TreeNode(*other.root) : nullptr;
    }
    
    ~BinStrTree() {
        delete root;
    }
    
    BinStrTree& operator=(const BinStrTree& other) {
        if (this != &other) {
            BinStrTree tmp(other); // Copy-constructor
            std::swap(root, tmp.root);
        }
        return *this;
    }
};
相关推荐
guizhoumen35 分钟前
PageAdmin开源网站无障碍/适老化工具条插件-让网站“看得清、听得懂“
c++·mfc
__万波__38 分钟前
嵌入式存储技术--1.Flash物理存储
java·开发语言
凯程序猿1号1 小时前
基于射线法与球面外积的WGS84电子围栏点在多边形内判定及边界容差算法
算法·电脑
Chen_harmony1 小时前
十六、ALV树
开发语言·c++
budingxiaomoli1 小时前
动态规划---子序列
算法·动态规划
释厄6231 小时前
尺子必回量与劣币生良币——可证伪明的尺子性·同源可转化
大数据·算法·开源
qq_274475151 小时前
第 28 篇:Promise 全解析:状态、then/catch/finally、静态方法 all/race/allSettled/any
开发语言·javascript
天诰2 小时前
SA-T-06 轨迹数据工程 脏数据检测
人工智能·python·算法·语言模型·ai编程
西西弗Sisyphus2 小时前
C++ 最小 Agentic Loop 实现 - 回调函数系列 - 初识回调(5)
开发语言·c++
程序员小杰@2 小时前
Java 统一报文转换 + 签名验签完整介绍
java·开发语言