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;
    }
};
相关推荐
艾莉丝努力练剑4 小时前
hixl vs NCCL:昇腾生态通信库的独特优势分析
运维·c++·人工智能·cann
执风挽^4 小时前
Python基础编程题2
开发语言·python·算法·visual studio code
我在人间贩卖青春4 小时前
C++之new和delete
c++·delete·new
Z9fish4 小时前
sse哈工大C语言编程练习20
c语言·开发语言·算法
Trouvaille ~4 小时前
TCP Socket编程实战(三):线程池优化与TCP编程最佳实践
linux·运维·服务器·网络·c++·网络协议·tcp/ip
晓13134 小时前
第六章 【C语言篇:结构体&位运算】 结构体、位运算全面解析
c语言·算法
iAkuya5 小时前
(leetcode)力扣100 61分割回文串(回溯,动归)
算法·leetcode·职场和发展
June`5 小时前
高并发网络框架:Reactor模式深度解析
linux·服务器·c++
梵刹古音5 小时前
【C语言】 指针与数据结构操作
c语言·数据结构·算法
VT.馒头5 小时前
【力扣】2695. 包装数组
前端·javascript·算法·leetcode·职场和发展·typescript