我開始創建一個二叉樹。到目前爲止,我所添加的是一個插入函數,我相信它工作正常。當我一起編譯我的應用程序,頭文件和實現文件時,它會生成一個可執行文件,但在其上面有一個關於所使用的異常處理程序的錯誤代碼。當我運行可執行文件時,它會崩潰。我不明白它爲什麼會崩潰,請有人幫忙!提前致謝。C++可執行文件崩潰
命令行錯誤http://gyazo.com/7ca1e8fb1a66da39e927e9ba627d3f53
我叫應用程序文件mainprogramming.cpp稱爲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;
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;
}
我的頭文件
#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";
}
當您使用調試器,並逐步通過每個語句時,哪個語句導致該問題? –
沒有在你的代碼中,你是否將'tree'設置爲'nullptr',所以'如果(tree == nullptr)'不會在第一次迭代中工作。 – NathanOliver
不知道哪個聲明導致和問題,然後我將如何解決該問題? –