2016-05-03 39 views
1

所以我的第一個C++程序,我想做出一點二叉樹但後根進入的第一個值後:這 - > m_xy是nullptr

拋出異常:寫訪問衝突。

this-> m_left was nullptr。

我的測試輸入:減少int數。

我的代碼:

#include<iostream> 

class BinaryTree 
{ 
public: 
    BinaryTree *m_left; 
    int m_key; 
    BinaryTree *m_right; 

    void insert(int value) 
    { 
     BinaryTree son; 

     if (value <= m_key) 
     { 
      if (m_left == NULL) 
       *m_left = { NULL, value, NULL }; //Error 
      else 
      (*m_left).insert(value); 
     } 
     //uniportant stuff ... 
    } 

    //unimportant stuff 
}; 

int main() 
{ 
int rootValue(0); 
std::cout << "Enter a value for the root: "; 
std::cin >> rootValue; 
std::cout<<std::endl; 

BinaryTree root = { NULL, rootValue, NULL }; 

int leafValue(1); 
std::cout << "Enter a value for the leaf or enter 0 to finish: "; 
std::cin >> rootValue; 
while (leafValue != 0) 
{ 
    root.insert(leafValue); 
    std::cout << "Enter a value for the leaf or enter 0 to finish: "; 
    std::cin >> rootValue; 
    std::cout << std::endl; 
} 

root.print(); 

return 0; 

} 
+1

看起來你去參考他們分配一個對象之前指針,它們不會自動創建。你需要在某處「新」他們等。 – Niall

+0

啊是的,thx :)。這幫助我做好準備! – Bubibob

回答

3

當您創建root節點,創建一個本地BinaryTree對象。

當你再插入你的第一個值,m_leftNULL,在以下分支:

if (m_left == NULL) 
    *m_left = { NULL, value, NULL }; // Assignment to a NULL pointer. 

會發生什麼?您可以取消引用空指針來複制對象。在這一點上,行爲是不確定的,註定要失敗。

在將任何內容分配給解除引用的指針* m_left之前,指針必須指向一個有效的對象。

如下,您可以更正分配:

m_left = new BinaryTree{ NULL, value, NULL }; 
+0

謝謝,這比我設法得到的更好:) – Bubibob

1

好了,問題就解決了。簡單地改變

 *m_left = { NULL, value, NULL }; 

 m_right = new BinaryTree; 
     (*m_right).m_left = NULL; 
     (*m_right).m_key = value; 
     (*m_right).m_right = NULL; 

THX尼爾