[英]Trouble overiding function of derived class
我在用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
};
您需要將要覆蓋的功能設為虛擬。 例如:
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 *的insert方法不會覆蓋具有Node *的方法。 相反,它將創建一個新的insert方法重載。
另外,要清楚一點,除非您打算在函數中更改指針的值(而不是指向的指針)並且希望該更改在調用者中可見,否則沒有理由通過引用傳遞指針。 通過引用傳遞只會添加不必要的取消引用(取決於上述警告)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.