【问题标题】:Destructor Code for Recursive Binary Tree Deletion Not Working In Visual C++ 2012递归二叉树删除的析构函数代码在 Visual C++ 2012 中不起作用
【发布时间】:2014-02-27 02:20:05
【问题描述】:

这个问题可能与其他一些问题相似;但是,我的问题与 Visual C++ 问题有关。以下用于删除二叉树的代码适用于 GNU 的 C++ 编译器。

Tree_Node 类定义:

class Tree_Node
{
    friend class Binary_Tree;

public:
    typedef int node_type;

    node_type& data()
    {
        return value;
    }

    void data(node_type key)
    {
        this->value = key;
    }

    Tree_Node(node_type key) : value(key) {}
    ~Tree_Node();


private:
    node_type value = 0;
    Tree_Node* right = nullptr;
    Tree_Node* left = nullptr;
};

二叉树析构函数定义:

Binary_Tree::~Binary_Tree()
{
    deleteTree(root);
}

void Binary_Tree::deleteTree(Tree_Node* node)
{
    if (node)
    {
        deleteTree(node->left);
        deleteTree(node->right);

        cout << node->data();
        delete node;
    }
}

但是,在尝试使用 Visual C++ 时,相同的代码出现了一些奇怪的错误:

错误 1 ​​错误 LNK2019: 无法解析的外部符号 "public: __thiscall Tree_Node::~Tree_Node(void)" (??1Tree_Node@@QAE@XZ) 中引用 函数“公共:无效* __thiscall Tree_Node::`标量删除 析构函数'(unsigned int)" (??_GTree_Node@@QAEPAXI@Z) E:\Workspace\BinaryTree\BinaryTree\BinaryTree_Methods.obj

错误 2 错误 LNK1120: 1 未解决的外部
E:\Workspace\BinaryTree\Debug\BinaryTree.exe

问题似乎是由delete node; 语句引起的。我在这里想念什么?

【问题讨论】:

  • Tree_Node.cpp 是否与 Binary_Tree.cpp 编译在同一个项目中?
  • 嗯,它们是同一个项目的一部分。类定义 Tree_Node 和 BinaryTree 位于单独的头文件 TreeHeader.h 中。 Binary_Tree 的方法定义在文件 BinaryTree_Methods.cpp 中。但是,是用 Visual C++ 编译的头文件
  • 检查您的Tree_Node 并确保在类decl 中有已实现 ~Tree_Node() 或没有~Tree_Node(); 声明。看起来您在类 decl 中声明了一个,但没有实现它。这是一个全有或全无的交易。您必须声明 实现它,或者不这样做并使用默认析构函数(这可能不适合您的情况,但这是一个不同的问题)。
  • 显示 Node 的定义和析构函数的定义(如果显式定义)。
  • @Chatterjee destructor,如果你需要默认破坏之外的东西(即你有自己的清理,你需要的不仅仅是允许你持有-价值枯萎)。在大多数情况下,只使用默认销毁就可以了,但有时并非如此。

标签: c++ visual-c++ binary-tree


【解决方案1】:

你有没有为节点创建析构函数?

Like 声明和定义~Tree_Node()

【讨论】:

  • 我的错! =default 成功了。我最初在考虑不同的删除策略,其中BinaryTree 将删除其root,而Tree_Node 析构函数将删除其leftright 子级,但尝试了这个并忘记实现Tree_Node析构函数。我很惊讶这如何与g++ 一起工作?
  • @Chatterjee 这不是原因。指定 = default 是析构函数的定义。
  • @VladfromMoscow 我的意思是我忘记定义 Tree_Node 析构函数;我只声明了它(请参阅上面的更新代码)。用=default 定义它使代码工作。
猜你喜欢
  • 1970-01-01
  • 2017-04-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-16
  • 2013-04-14
  • 2013-06-15
  • 2019-01-18
相关资源
最近更新 更多