TypeError:'addNode'不是函数

时间:2018-06-10 19:08:57

标签: javascript p5.js

我编写了一个简单的JavaScript p5应用程序(使用p5.js)来创建BST数据结构。使用Firefox运行时,它显示a.cpp: In member function ‘void A::Hi()’: a.cpp:9:10: error: invalid use of incomplete type ‘class A::B’ this->b_->Hi(); ^ In file included from a.cpp:2:0: a.hpp:12:8: error: forward declaration of ‘class A::B’ class B; ^ In file included from /usr/include/c++/4.9/memory:81:0, from a.hpp:4, from a.cpp:2: /usr/include/c++/4.9/bits/unique_ptr.h: In instantiation of ‘typename std::_MakeUniq<_Tp>::__single_object std::make_unique(_Args&& ...) [with _Tp = A::B; _Args = {}; typename std::_MakeUniq<_Tp>::__single_object = std::unique_ptr<A::B>]’: a.cpp:4:36: required from here /usr/include/c++/4.9/bits/unique_ptr.h:765:69: error: invalid use of incomplete type ‘class A::B’ { return unique_ptr<_Tp>(new _Tp(std::forward<_Args>(__args)...)); } ^ In file included from a.cpp:2:0: a.hpp:12:8: error: forward declaration of ‘class A::B’ class B; ^ In file included from /usr/include/c++/4.9/memory:81:0, from a.hpp:4, from a.cpp:2: /usr/include/c++/4.9/bits/unique_ptr.h: In instantiation of ‘void std::default_delete<_Tp>::operator()(_Tp*) const [with _Tp = A::B]’: /usr/include/c++/4.9/bits/unique_ptr.h:236:16: required from ‘std::unique_ptr<_Tp, _Dp>::~unique_ptr() [with _Tp = A::B; _Dp = std::default_delete<A::B>]’ a.cpp:4:36: required from here /usr/include/c++/4.9/bits/unique_ptr.h:74:22: error: invalid application of ‘sizeof’ to incomplete type ‘A::B’ static_assert(sizeof(_Tp)>0,
有人可以帮忙吗?这是完整的代码(错误在第20行)

TypeError: this.root.addNode is not a function

2 个答案:

答案 0 :(得分:1)

root只是您稍后分配为Node的属性。您将原型函数addNode分配给TreeNode没有。设置

this.root = new Tree();

或者将原型方法addNode分配给Node

答案 1 :(得分:0)

如果您感兴趣,可以使用class关键字来实现它,它可以为您处理大量的手动原型处理,因此它更容易出错。

class Node {
  constructor(key) {
    this.key = key;
    this.left = null;
    this.right = null;
  }
}

class Tree {
  constructor() {
    this.root = null;
  }

  _insert(target, key) {
    if (target.key > key) {
      if (!target.left) {
        target.left = new Node(key);
      } else {
        this._insert(target.left, key);
      }
    } else {
      if (!target.right) {
        target.right = new Node(key);
      } else {
        this._insert(target.right, key);
      }
    }
  }

  insert(key) {
    if (!this.root) {
      this.root = new Node(key);
    } else {
      this._insert(this.root, key);
    }
  }
}