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;
    }
};
相关推荐
hhzz9 分钟前
机器学习-算法模型系列文章:07-SVM 一巴掌拍出来的超平面:SVM核函数选错,再干净的数据也救不了你
算法·机器学习·支持向量机
ShuiShenHuoLe20 分钟前
Go html/template 使用入门
开发语言·golang·html
geovindu21 分钟前
java: Gale-Shapley Algorithm
java·开发语言·后端·算法
独隅37 分钟前
CLion 接入 Codex 的完整配置使用全面指南
c++·ide·ai·c++23
冻柠檬飞冰走茶41 分钟前
PTA基础编程题目集 7-34 通讯录的录入与显示(C语言实现)
c语言·开发语言·数据结构·算法
zander2581 小时前
LeetCode 79. 单词搜索
算法·深度优先
星核0penstarry1 小时前
DeepSeek-V4-Flash 正式公测:大模型行业进入「极速平价普惠时代」
java·开发语言·人工智能
老洋葱Mr_Onion1 小时前
【C++】高精度模板
开发语言·c++·算法
脚踏实地皮皮晨1 小时前
003003002_WPF Grid 基类官方类定义逐行深度解析
开发语言·windows·算法·c#·wpf·visual studio