不理解给定代码的输出

Don't understand the output of the given code

本文关键字:输出 代码 不理解      更新时间:2023-10-16

刚刚跳入C++并尝试运行以下代码:

#include <iostream>
using namespace std;

class BST_Node{
private:
int val;
BST_Node* left;
BST_Node* right;
public:
void setVal(int);
int getVal();
void setLeft(BST_Node*);
BST_Node* getLeft();
void setRight(BST_Node*);
BST_Node* getRight();
BST_Node(int val){this->val=val;this->left=nullptr;this->right=nullptr;}
};
class BST{
private:
BST_Node* root;
public:
void setBSTRoot(BST_Node* node){root=node;}
BST_Node* getBSTRoot(){return this->root;}
};
BST createBST(int*, int);
void placeNode(BST_Node*, int);
void BST_Node::setVal(int val){
this->val = val;
cout<<"11: "<< val << endl;
}
int BST_Node::getVal(){
return this->val;
}
void BST_Node::setLeft(BST_Node* left){
this->left = left;
}
void BST_Node::setRight(BST_Node* right){
this->right = right;
}
BST_Node* BST_Node::getLeft(){
return this->left;
}
BST_Node* BST_Node::getRight(){
return this->right;
}
void print_inorder(BST_Node root){
cout<<"working"<<endl;
if(root.getLeft()!=nullptr){
print_inorder(*(root.getLeft()));
}
cout<<"*"<<root.getLeft()->getVal() <<"*" << endl;
cout<<"*"<<root.getVal() <<"*" << endl;
cout<<"*"<<root.getRight()->getVal() <<"*" << endl;
}

BST createBST(int* arr, int arr_size){
BST obj_bst;
BST_Node* root;
cout<<"0 "<<endl;
root = obj_bst.getBSTRoot();
cout<<"1: "<< (*arr) << endl;
//cout<<"create BST " << root->getVal() <<endl;
root->setVal(*arr);
cout<<"2 "<<endl;
cout<<"create BST " << root->getVal() <<endl;
for(int i=1;i<arr_size;i++){
cout<<"create BST " << root->getVal() <<endl;
int curr_val = *(arr+i);
placeNode(root,curr_val);
}
cout<<"create BST " << root->getVal() <<endl;
return obj_bst;
}
void placeNode(BST_Node* root, int curr_val){
int root_val = root->getVal();
if((curr_val>root_val) && (root->getRight()!=nullptr) ){
placeNode(root->getRight(), curr_val);
}else if((curr_val<=root_val) && (root->getLeft()!=nullptr)){
placeNode(root->getLeft(), curr_val);
}else if((curr_val>root_val) && (root->getRight()==nullptr)){

BST_Node node(curr_val);
root->setRight(&node);
}else if((curr_val<=root_val) && (root->getLeft()==nullptr)){
BST_Node node(curr_val);
root->setLeft(&node);
}else{
cout<< "Placement denied" << endl;
}
}
//void createBST(int* arr, int arr_size);
int main(){
int arr[10] = {23,23,34,1,2,343,343,23,4343};
cout<<"working"<<endl;
BST obj_bst = createBST(arr, 10);//sizeof(arr)/sizeof(int)
cout<<"working"<<endl;
BST_Node root = *(obj_bst.getBSTRoot());
cout<<"working"<<endl;
print_inorder(root);
cout<<"working"<<endl;
return 0;
}

我得到的输出是: " 加工 0 1: 23 " 执行在"createBST"方法中的"root->setVal(*arr(;"行之后停止。任何解释将不胜感激。谢谢!

对不起,代码太多了。我不知道这里还能做些什么来发布这个问题。

创建obj_bst后,不要将值设置为BST::root。因此,obj_bst.getBSTRoot()返回一个无效的指针,您调用该指针setVal从而导致崩溃。