我正在爲C++開發一個用於數據結構類的模板化二叉搜索樹。到現在爲止,一切進展順利。這個問題涉及一些我不熟悉的基本C++東西,我需要幫助。C++函數指針轉換
我以前定義了遍歷樹並以不同順序訪問每個節點的函數。這裏討論的問題定義如下。
TreeNode.h
public:
static void PostOrderVisit(TreeNode<T>* node, void visit(const T& v));
TreeNode.cpp
template <class T> void TreeNode<T>::PostOrderVisit(TreeNode* node, void visit(const T& v)) {
if (node->leftChild != NULL)
PostOrderVisit(node->leftChild, visit);
if (node->rightChild != NULL)
PostOrderVisit(node->rightChild, visit);
visit(node->value);
}
這工作正常的測試程序,使節點和靜態調用PostOrderVisit。在一個朋友類(BinSTree.h/cpp)中,我實現了刪除樹中每個節點的方法,所以我認爲使用這個訪問者並調用我的Delete()函數是一個好主意每個節點(Delete()函數在BinSTree的測試程序中也能正常工作)。
該功能定義如下。
template <class T> void BinSTree<T>::ClearTree() {
TreeNode<T>::PostOrderVisit(this->root(), &BinSTree<T>::Delete);
}
這裏存在問題。 G ++說...
BinSTree.cpp:156: error: no matching function for call to ‘TreeNode<int>::PostOrderVisit(TreeNode<int>*, void (BinSTree<int>::*)(const int&))’
TreeNode.cpp:56: note: candidates are: static void TreeNode<T>::PostOrderVisit(TreeNode<T>*, void (*)(const T&)) [with T = int]
在這種情況下,我認爲void (BinSTree<T>::*)(const T&)
將是void (*)(const T&)
的實例,但事實並非如此。我可以調用的唯一辦法由函數定義的認可是由鑄造函數指針這樣的:
TreeNode<T>::PostOrderVisit(this->root(), (void (*)(const T& v)) &BinSTree<T>::Delete);
此識別功能,並適當地調用它,但是(這花了一些顯著的研究... ),C++成員函數有一個隱式參數,允許從內部訪問'this'關鍵字。將一個成員函數指針投射到一個普通函數指針上會完全拋棄'this'引用,從而導致我的Delete()方法分段錯誤(它使用'this'相當多)。
這一直是一個麻煩的地獄,我花了很多時間在這個項目的這麼一點點。任何人都可以向我展示一種方法:A:讓該功能在沒有投射的情況下被識別,或者B:如何在整個演員中保持這個「這個」參考。 ClearTree()和Delete()方法都在同一個類中。
在此先感謝。
如果您已經在使用模板,請跳過函數指針並直接進入函子。可以內聯非虛擬的非函數指針調用。讓'visit'可以重載'operator()()'的模板。 – asveikau 2012-04-10 07:09:13