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;
    }
};
相关推荐
飞机和胖和黄15 小时前
王道考研C语言第五周
c语言·考研·算法
fpcc15 小时前
跟我学C++中级篇—线程局部存储的底层分析
c++
£漫步 云端彡15 小时前
Golang学习历程【第十二篇 错误处理(error)】
开发语言·学习·golang
市场部需要一个软件开发岗位16 小时前
一个无人机平台+算法监督平台的离线部署指南
java·python·算法·bash·无人机·持续部署
ygklwyf16 小时前
零基础薄纱树套树——高级数据结构的结合
算法·线段树·树状数组·树套树
Cinema KI16 小时前
C++11(中):可变参数模板将成为重中之重
开发语言·c++
凯子坚持 c16 小时前
C++基于微服务脚手架的视频点播系统---客户端(2)
开发语言·c++·微服务
Vivienne_ChenW16 小时前
Spring 事件驱动用法总结
java·开发语言·spring boot·spring
Beginner x_u16 小时前
JavaScript 中浅拷贝与深拷贝的差异与实现方式整理
开发语言·javascript·浅拷贝·深拷贝
柯一梦16 小时前
STL2--vector的介绍以及使用
开发语言·c++