【问题标题】:Trouble overiding function of derived class麻烦覆盖派生类的函数
【发布时间】:2012-10-02 05:45:16
【问题描述】:

我在使用 AVL 树调用覆盖函数时遇到了一些问题。它正在调用 BST 树中的那个。这比平常更令人困惑,因为 AVLNode 是从 BinaryNode 派生的。我需要添加一个高度数据成员。这可能是导致问题的原因还是比这更简单。

class BST
{
     public:
     Parent():root(NULL) { }
     void insert( const string & x, int lineNum, int& count )
     {
           insert(x, lineNum, root, count);
     }

     protected:
     BinaryNode* root;
     void insert( const string & x, int lineNum, Node * & t, int& count )
     {//stuff
     }
};

class AVL:public BST
{
     public:
     void insert( const string & x, int lineNum, int& count )
     {
        cout << "INSERT\n";   
        insert(x, lineNum, root, count);
     }
     protected:
     AVLNode* root;

     void insert( const string & x, int lineNum, AVLNode * & t, int& count )
     {
          cout << "insert\n";   
        //different stuff
     }
};

class BinaryNode
{//constructors
}

class AVLNode:public BinaryNode
{//constructors
};

【问题讨论】:

  • 如何创建 AVL 树以及如何调用方法?

标签: c++ inheritance overriding


【解决方案1】:

您需要将要覆盖的函数设为虚拟函数。例如:

 virtual void insert( const string & x, int lineNum, int& count )
 {
       insert(x, lineNum, root, count);
 }

 virtual void insert( const string & x, int lineNum, Node * & t, int& count )
 {//stuff
 }

带有 AVLNode* 的插入方法不会覆盖带有 Node* 的方法。它将创建一个新的 insert 方法重载。

另外,为了清楚起见,没有理由通过引用传递指针,除非您打算更改函数中指针(而不是指向)的值并且希望更改在调用者中可见。通过引用传递只会添加不必要的取消引用(受上述警告的约束)。

【讨论】:

  • 添加虚拟似乎已经解决了一些问题。它修复了插入,但是当我仍然遇到覆盖和返回 AVLNodes 而不是 BSTNodes 的函数时。这不可能吗?
  • 如果你想要改变的只是返回类型,你可能会得到一个错误(我愿意)。如果您要更改参数中的任何内容(例如您提供 Node->AVLNode 的示例),它将重载而不是覆盖。
猜你喜欢
  • 1970-01-01
  • 2015-06-28
  • 2013-04-27
  • 2018-12-23
  • 2013-09-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-24
相关资源
最近更新 更多