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;
}
};