首先,我的树由看起来像这样的节点组成:
struct Node
{
string name;
Node *left; //points to the left child
Node *right; //points to the right child
};
对于我的拷贝构造函数,我有一个辅助函数,它在root中传递,我这样调用它(在我的拷贝构造函数中):
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>'
答案 0 :(得分:4)
正如错误消息所述,正在尝试将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);
}