我开始创建一个二叉树。到目前为止,我添加的是一个插入函数,我相信它工作正常。当我将我的应用程序,头文件和实现文件编译在一起时,它会生成一个可执行文件,但上面有一个关于异常处理程序的错误代码....当我去运行可执行文件时它会崩溃。我不明白为什么会崩溃,有人可以帮忙!提前谢谢。
命令行错误http://gyazo.com/7ca1e8fb1a66da39e927e9ba627d3f53
我的应用程序文件名为mainprogramming.cpp
#include <iostream>
#include <cstdlib>
#include "Header.h"
using namespace std;
int main()
{
int Rndnums[10] = {3, 99, 76, 49, 32, 9, 77, 64, 81, 24};
BinaryTree *tree = new BinaryTree();
for(int i = 0; i < 10; i++)
{
tree->insert(Rndnums[i]);
}
return 0;
}
我的头文件名为Header.h
class BinaryTree
{
// Can only be accessed by the class itself
private:
struct node
{
// Data stored in this node of he tree
int data;
// The left branch of the tree
node *left;
// The right branch of the tree
node *right;
};
node *tree;
void insert(node *tree, int value);
// Can be accessed by all
public:
BinaryTree(){};
~BinaryTree();
void insert(int value);
};
我的实现文件名为implementation.cpp
#include <iostream>
#include <cstdlib>
#include "Header.h"
using namespace std;
// Inserts a value into the tree - notice **
void BinaryTree::insert(node *tree, int value)
{
// Check if nullptr. If so set new node
if (tree == nullptr)
{
// Create new node
tree = new node;
// Set new value
tree->data = value;
// Set branches to nullptr
tree->left = nullptr;
tree->right = nullptr;
}
// If the input value is less than the node in the tree
else if(value < tree->data)
{
insert(tree->left, value);
cout << "The value " << value << "has been added as a left child\n";
}
// If the input value is greater than the node in the tree
else if(value > tree->data)
{
insert(tree->right, value);
cout << "The value " << value << "has been added as a right child\n";
}
else
{
cout << "The value " << value << "can only be equal and must already exist in the tree\n";
}
}
void BinaryTree::insert(int value)
{
insert(this->tree, value);
cout << "It ran";
}
答案 0 :(得分:1)
您的问题出在您的插入电话中:
void BinaryTree::insert(node * leaf_head, int value)
{
...
}
您正在复制指针地址,然后尝试在该内存空间中创建一个对象,然后修改该对象。将它更改为对该指针的引用时,它可以正常工作:
void BinaryTree::insert(node * & leaf_head, int value)
{
...
}
这样你实际上是修改了tree
中的BinaryTree
指针,而不是它的副本。