2012-04-02 72 views
0

我所有的樹首先是由節點看起來像這樣:寫一個輔助函數的二叉搜索樹的拷貝構造函數

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

我需要包括任何其他的助手,爲什麼正在創建在堆上的字符串,當我收到這個錯誤?

在絃線的錯誤是:

Error 1 error C2440: 'initializing' : cannot convert from 'std::string *' to 'std::basic_string<_Elem,_Traits,_Ax>' 
+0

爲什麼不字符串需要一個新的? – dev6546 2012-04-02 20:03:20

回答

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