首先,我的树由如下节点组成:
struct Node
{
string name;
Node *left; //points to the left child
Node *right; //points to the right child
};
对于我的复制构造函数,我有一个在根中传递的助手函数,我这样调用它(在复制构造函数中):
root = Helper(base.root);
现在,对于copyHelper的主体,我需要一些帮助来复制每个节点的实际字符串。
Node* newNode = new Node;
string newName = new string;
newName = other->name;
newNode->name = newName;
newNode->left = Helper(other->left);
newNode->right = Helper(other->right);
我需要在Helper中包含其他内容吗?为什么在堆上创建字符串时会出现错误?
字符串行上的错误为:
Error 1 error C2440: 'initializing' : cannot convert from 'std::string *' to 'std::basic_string<_Elem,_Traits,_Ax>'
正如错误消息所述,正在尝试将string*
分配给string
。纠正错误:
string newName;
不需要在堆上创建string
对象。此外,似乎根本没有理由使用newName
:
Node* newNode = new Node;
if (newNode)
{
newNode->name = other->name;
newNode->left = Helper(other->left);
newNode->right = Helper(other->right);
}