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;
    }
};
相关推荐
VBA633726 分钟前
VBA即用型代码手册:利用函数保存为PDF文件UseFunctionSaveAsPDF
开发语言
say_fall28 分钟前
C语言编程实战:每日刷题 - day2
c语言·开发语言·学习
上去我就QWER2 小时前
Qt快捷键“魔法师”:QKeySequence
开发语言·c++·qt
Pluto_CSND4 小时前
Java中的静态代理与动态代理(Proxy.newProxyInstance)
java·开发语言
将编程培养成爱好4 小时前
C++ 设计模式《外卖骑手状态系统》
c++·ui·设计模式·状态模式
猿太极4 小时前
设计模式学习(3)-行为型模式
c++·设计模式
惊讶的猫5 小时前
LSTM论文解读
开发语言·python
cynicme6 小时前
力扣3228——将 1 移动到末尾的最大操作次数
算法·leetcode
熬了夜的程序员6 小时前
【LeetCode】109. 有序链表转换二叉搜索树
数据结构·算法·leetcode·链表·职场和发展·深度优先
獨枭6 小时前
C# 本地项目引用失效与恢复全攻略
开发语言·c#·visual studio