【发布时间】:2016-03-16 16:57:48
【问题描述】:
对于我在学校从事的一个项目,我必须将一个指向一个对象的指针插入两个 BST。一个 BST 按 APN(唯一键)排序,另一个按价格排序(非唯一)。我们正在使用模板,所以我问我的教授如何做到这一点,她说使用函数指针。当我尝试这样做时,遇到了一些我不知道如何解决的错误。
对象被定义为
class House
{
private:
string APN; // Unique key
int price; // Non-unique key
string address;
int bedrooms;
double bathrooms;
int sqFt;
}
在 main 中,创建对象后我尝试运行。
uniqueTree->insert(newHouse, comparePrimaryKey);
nonUniqueTree->insert(newHouse, compareSecondaryKey);
每个函数定义为
int comparePrimaryKey(const House* &left, const House* &right)
{
if(left->getAPN() < right->getAPN())
return -1;
else
return 1;
}
int compareSecondaryKey(const House* &left, const House* &right)
{
if(left->getPrice() < right->getPrice()) // right > left
return -1;
else // right < left
return 1;
}
但我收到一个错误提示
"Cannot initialize a parameter of type 'int (*)(House *const &, House *const &)
with an lvalue of type 'int (const House *&, const House *&)'"
二叉树文件中有一个名为rootPtr的BinaryNode对象指针,insert定义为纯虚函数。
BinaryNode<ItemType>* rootPtr;
virtual bool insert(const ItemType & newData, int compare(const
ItemType&, const ItemType&)) = 0;
二进制节点类:
template<class T>
class BinaryNode
{
private:
T item; // Data portion
BinaryNode<T>* leftPtr; // Pointer to left child
BinaryNode<T>* rightPtr; // Pointer to right child
public:
// constructors
BinaryNode(const T & anItem) {item = anItem; leftPtr = 0; rightPtr = 0;}
BinaryNode(const T & anItem,
BinaryNode<T>* left,
BinaryNode<T>* right) {item = anItem; leftPtr = left; rightPtr = right;}
// mutators
void setItem(const T & anItem) {item = anItem;}
void setLeftPtr(BinaryNode<T>* left) {leftPtr = left;}
void setRightPtr(BinaryNode<T>* right) {rightPtr = right;}
// accessors
T getItem() const {return item;}
BinaryNode<T>* getLeftPtr() const {return leftPtr;}
BinaryNode<T>* getRightPtr() const {return rightPtr;}
bool isLeaf() const {return (leftPtr == 0 && rightPtr == 0);}
};
在BST文件中,insert定义为
template<class ItemType>
bool BinarySearchTree<ItemType>::insert(const ItemType &newEntry, int
compare(const ItemType &, const ItemType &))
{
BinaryNode<ItemType>* newNodePtr = new BinaryNode<ItemType>(newEntry);
BinaryTree<ItemType>::rootPtr = _insert(BinaryTree<ItemType>::rootPtr,
newNodePtr, compare(newNodePtr->getItem(), BinaryTree<ItemType>::rootPtr()->getItem()));
return true;
}
我在 BinaryTree::rootPtr 行也收到错误提示
Called object type 'BinaryNode<House *> *' is not a function or function pointer
【问题讨论】:
-
尝试将 comparePrimaryKey(const House* &left, const House* &right) 改为 comparePrimaryKey(const House* left, const House* right)
标签: c++ templates compiler-errors binary-search-tree function-pointers