关于复制控制成员的一点疑问
本帖最后由 wsfxzxb 于 2012-12-19 12:55:20 编辑 对于如下的类,实现默认构造函数和必要的复制控制成员
class TreeNode
{
public:
// ...
private:
string value;
int count;
TreeNode *left;
TreeNode *right;
};
class TreeNode
{
public:
TreeNode():count(0),left(0),right(0){} // 默认构造函数
TreeNode(const TreeNode &tn) // 复制构造函数(复制指针指向的对象)
{
value=tn.value;
count=tn.count;
left=(tn.left==0) ? 0 : new TreeNode(*tn.left);
right=(tn.right==0) ? 0 : new TreeNode(*tn.right);
}
TreeNode& operator=(const TreeNode &tn) // 赋值操作符
{
value=tn.value;
count=tn.count;
*left=*tn.left;
*right=*tn.right;
return *this;
}
~TreeNode() // 析构函数(删除new分配的指针)
{
if(left)
delete left;
if(right)
delete right;
}
private:
string value;
int count;
TreeNode *left;
TreeNode *right;
};