【发布时间】:2019-03-31 04:01:33
【问题描述】:
我正在制作一个二叉树模板类,虽然这个特殊的运行时错误从未发生过用整数初始化 BST,但我还没有解决它用字符串初始化 BST。错误发生在标记线上。
#ifndef BST_H
#define BST_H
#include "BSTInterface.h"
template <typename T>
class BST : public BSTInterface<T>
{
public:
BST()
{
root = new Node;
root = NULL;
}
bool addNode(const T& newVal, Node *start)
{
start->data = newVal; // ERROR HERE
return true;
}
private:
struct Node
{
T data;
Node *left;
Node *right;
};
Node *root;
};
#endif
我尝试将 root 的每个值都设置为 null,但我得到了这个构建错误:
BST.h(18): error C2593: 'operator =' is
ambiguous
第 18 行是我将 start->data 设置为 null 的地方。将 start->left 和 start->right 设置为 null 不会产生构建错误。
我必须能够将这些设置为 null 而不是某个任意值,以便其他代码(我不允许修改)工作。任何帮助将不胜感激。
编辑:包括过度最小化的副作用。
#include "BST.h"
int main(int argc, char * argv[])
{
BST<std::string> myBST;
myBST.addNode("e");
}
BST 中的附加函数,实际上是从 main 调用的:
bool addNode(const T& newVal)
{
return addNode(newVal, root);
}
编辑 2:BSTInterface 的代码
//**** YOU MAY NOT MODIFY THIS DOCUMENT ****/
#ifndef BST_INTERFACE_H
#define BST_INTERFACE_H
#include <string>
/** A binary tree node with data, left and right child pointers */
template<typename T>
class BSTInterface
{
public:
BSTInterface(void) {}
virtual ~BSTInterface(void) {}
/** Return true if node added to BST, else false */
virtual bool addNode(const T&) = 0;
/** Return true if node removed from BST, else false */
virtual bool removeNode(const T&) = 0;
/** Return true if BST cleared of all nodes, else false */
virtual bool clearTree() = 0;
/** Return a level order traversal of a BST as a string */
virtual std::string toString() const = 0;
};
#endif // BST_INTERFACE_H
【问题讨论】:
-
你需要一个完整的例子。你还没有展示你是如何尝试使用你的代码的。
-
与your rubber duck讨论
root = new Node; root = NULL; -
如果我不包含这两行,或者至少以某种方式将 root 设置为 null,则不可修改的代码(打印功能)将无法正常工作。没有经验能够解决这个问题。
-
永远不要为了让代码神奇地“工作”而引入错误(将 null 赋值给 root)。
-
@TroubledProgrammer 你分配了一个新的
Node,将指向它的指针存储在root,然后立即将NULL存储在root中,丢失指向新的Node的指针你只是分配。那是毫无意义的内存泄漏。分配新节点的目的是什么?