C++ 析构函数中的堆栈溢出

Rz4*_*Rz4 4 c++ stack-overflow destructor

我尝试创建 detor 并得到一个“堆栈溢出”我知道为什么但我希望它的工作......

#include <iostream>
#include "printTreeToFile.h"
#include "BSNode.h"
#define _BS BSNode::
#define _BSNode _BS BSNode
_BS ~BSNode()
{
    Del(this);
}
void _BS Del(BSNode *x,int y)
{
    if (x->isLeaf())
    {
        delete x;
        return;
    }
    if (x->_Right != NULL)
        Del(x->_Right,y += 1);
    if (x->_Left != NULL)
        Del(x->_Left,y += 1);
    if (y != 1)
    {
        delete x;
    }
    return;
}
Run Code Online (Sandbox Code Playgroud)

我尝试以递归方式执行此操作,但是对 Del 的删除调用因此我们获得了无限循环

use*_*421 5

_BS ~BSNode()
{
    Del(this);
}

void _BS Del(BSNode *x,int y)
{
    if (x->isLeaf())
    {
        delete x;
        return;
    }
    if (x->_Right != NULL)
        Del(x->_Right,y += 1);
    if (x->_Left != NULL)
        Del(x->_Left,y += 1);
    if (y != 1)
    {
        delete x;
    }
    return;
}
Run Code Online (Sandbox Code Playgroud)

您正在this递归删除。你不需要这一切。你想多了。所有你需要的是:

BSNode::~BSNode()
{
    delete _Left;
    delete _Right;
}
Run Code Online (Sandbox Code Playgroud)

这将自动向下递归左子树和右子树,并在空值处停止。