这个 -> m_xy 是一个 nullptr
this -> m_xy was a nullptr
因此,作为我的第一个 C++ 程序,我想制作一个小二叉树,但在输入根后的第一个值后:
抛出异常:写入访问冲突。
this->m_left 是 nullptr。
我的测试输入:减少整数。
我的代码:
#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;
}
当您创建 root
节点时,您会创建一个本地 BinaryTree
对象。
当您随后插入第一个值时,m_left
是 NULL
,在以下分支中:
if (m_left == NULL)
*m_left = { NULL, value, NULL }; // Assignment to a NULL pointer.
会发生什么?您取消引用空指针以复制对象。此时的行为是未定义的,注定要失败。
在向取消引用的指针 *m_left 分配任何内容之前,该指针必须指向一个有效的对象。
您可以按如下方式更正作业:
m_left = new BinaryTree{ NULL, value, NULL };
好的,问题解决了。简单地改变了
*m_left = { NULL, value, NULL };
进入
m_right = new BinaryTree;
(*m_right).m_left = NULL;
(*m_right).m_key = value;
(*m_right).m_right = NULL;
谢谢尼尔
因此,作为我的第一个 C++ 程序,我想制作一个小二叉树,但在输入根后的第一个值后:
抛出异常:写入访问冲突。
this->m_left 是 nullptr。
我的测试输入:减少整数。
我的代码:
#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;
}
当您创建 root
节点时,您会创建一个本地 BinaryTree
对象。
当您随后插入第一个值时,m_left
是 NULL
,在以下分支中:
if (m_left == NULL)
*m_left = { NULL, value, NULL }; // Assignment to a NULL pointer.
会发生什么?您取消引用空指针以复制对象。此时的行为是未定义的,注定要失败。
在向取消引用的指针 *m_left 分配任何内容之前,该指针必须指向一个有效的对象。
您可以按如下方式更正作业:
m_left = new BinaryTree{ NULL, value, NULL };
好的,问题解决了。简单地改变了
*m_left = { NULL, value, NULL };
进入
m_right = new BinaryTree;
(*m_right).m_left = NULL;
(*m_right).m_key = value;
(*m_right).m_right = NULL;
谢谢尼尔