【问题标题】:Creating new instance of class using template, don't know how to handle error使用模板创建类的新实例,不知道如何处理错误
【发布时间】:2012-06-13 09:53:31
【问题描述】:

我会尽量保持代码简短。

我正在尝试使用模板制作一个 B inary S 搜索 T ree(简称 BST)。

在我的添加函数中,我遇到了一个错误,我确定我以某种方式滥用了模板

由于模板,所有这些代码都在一个 .h(头文件)文件中。

编辑: const Type & 错误是因为我摆弄,它实际上不在我编译的代码中,而是来自上一个关于堆栈溢出的问题

template <typename Type>
class BSTNode {   // Binary Search Tree nodes
  private:
    int key;      // we search by key, no matter what type of data we have
    Type data;
    BSTNode *left;
    BSTNode *right;

  public:
    BSTNode (int, Type);     // key, data
    bool add (int, Type);
};

添加函数:

template <typename Type>
bool BSTNode<Type>::add(int newKey, Type newData) {
  if (newKey < this->key) {
    if (left == NULL) {
      this->left = new BSTNode<Type>(int newKey, Type newData);
    }
  } else {
    this->right = new BSTNode<Type>(int newKey, Type newData);
  }
  return false;
}

这是我得到错误的地方:

this->left = new BSTNode<Type>(int newKey, Type newData);

int 之前的预期主表达式

【问题讨论】:

  • 我们已经知道 BST 代表什么。 ;)

标签: c++ templates pointers binary-search-tree dereference


【解决方案1】:

您不是专门滥用模板,而是滥用参数!

this->left = new BSTNode<Type>(int newKey, Type newData); 

应该看起来更像

this->left = new BSTNode<Type>(newKey, newData); 

【讨论】:

  • 谢谢,这成功了!不知道我是怎么错过的,但我现在看了半个小时的代码,得到了隧道视觉。
【解决方案2】:

应该是this-&gt;left = new BSTNode&lt;Type&gt;(newKey, newData);,不带任何类型。

【讨论】:

    【解决方案3】:

    错误很明显:

     bool add (int, Type);
    

     bool add(int newKey, const Type &newData)
    

    您应该将类​​定义中的声明更改为:

     bool add (int, const Type&);
    

    并从语句中删除类型:

     this->right = new BSTNode<Type>(int newKey, Type newData);
     this->right = new BSTNode<Type>(int newKey, Type newData);
    

    应该是

     this->right = new BSTNode<Type>(newKey, newData);
     this->right = new BSTNode<Type>(newKey, newData);
    

    【讨论】:

    • 好的,现在解决了,不知道我怎么错过了,估计我会去指责隧道视野
    猜你喜欢
    • 1970-01-01
    • 2012-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-26
    • 1970-01-01
    相关资源
    最近更新 更多