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;
    }
};
相关推荐
弱冠少年19 分钟前
websockets库使用(基于Python)
开发语言·python·numpy
长天一色19 分钟前
C语言日志类库 zlog 使用指南(第五章 配置文件)
c语言·开发语言
MinBadGuy27 分钟前
【GeekBand】C++设计模式笔记5_Observer_观察者模式
c++·设计模式
一般清意味……31 分钟前
快速上手C语言【上】(非常详细!!!)
c语言·开发语言
自由的dream32 分钟前
0-1背包问题
算法
卑微求AC32 分钟前
(C语言贪吃蛇)16.贪吃蛇食物位置随机(完结撒花)
linux·c语言·开发语言·嵌入式·c语言贪吃蛇
2401_8572979138 分钟前
招联金融2025校招内推
java·前端·算法·金融·求职招聘
技术无疆42 分钟前
【Python】Streamlit:为数据科学与机器学习打造的简易应用框架
开发语言·人工智能·python·深度学习·神经网络·机器学习·数据挖掘
金灰1 小时前
HTML5--裸体回顾
java·开发语言·前端·javascript·html·html5
爱上语文1 小时前
Java LeetCode每日一题
java·开发语言·leetcode