所以我的第一個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;
}
看起來你去參考他們分配一個對象之前指針,它們不會自動創建。你需要在某處「新」他們等。 – Niall
啊是的,thx :)。這幫助我做好準備! – Bubibob