我目前有一个二叉搜索树设置,利用模板允许我轻松地更改二叉搜索树中的数据类型。目前,我无法重载包含要存储在树中的数据的studentRecord类。我需要重载此类中的比较运算符,以便我的BST可以根据其中的一个内容(在本例中为学生ID)正确比较两个对象。但是,尽管在studentRecord中重载了运算符,但正确的比较仍然没有发生。下面运算符使用BST中的模板进行重载
详情:
目前,在BST对象studentTree已创建类型,
bst<studentRecord *> studentTree;
studentRecord是下面的类:
// studentRecord class
class studentRecord{
public:
// standard constructors and destructors
studentRecord(int studentID, string lastName, string firstName, string academicYear){ // constructor
this->studentID=studentID;
this->lastName=lastName;
this->firstName=firstName;
this->academicYear=academicYear;
}
friend bool operator > (studentRecord &record1, studentRecord &record2){
if (record1.studentID > record2.studentID)
cout << "Greater!" << endl;
else
cout << "Less then!" << endl;
return (record1.studentID > record2.studentID);
}
private:
// student information
string studentID;
string lastName;
string firstName;
string academicYear;
};
每当新项目被添加到我的BST,他们必须相互比较。因此,我想重载studentRecord类,以便在比较过程发生时,比较studentID(否则将进行无效比较)。
但是,我的插入函数从不使用我的重载比较函数。相反,它似乎是以另一种方式比较两个对象,导致BST内的无效排序。我的插入函数的一部分在下面 - 重要的是要注意,由于模板过程发生,toInsert和nodePtr->数据都应该是studentRecord类型。
// insert (private recursive function)
template<typename bstType>
void bst<bstType>::insert(bstType & toInsert, bstNodePtr & nodePtr){
// check to see if the nodePtr is null, if it is, we've found our insertion point (base case)
if (nodePtr == NULL){
nodePtr = new bst<bstType>::bstNode(toInsert);
}
// else, we are going to need to keep searching (recursive case)
// we perform this operation recursively, to allow for rotations (if AVL tree support is enabled)
// check for left
else if (toInsert < (nodePtr->data)){ // go to the left (item is smaller)
// perform recursive insert
insert(toInsert,nodePtr->left);
// AVL tree sorting
if(getNodeHeight(nodePtr->left) - getNodeHeight(nodePtr->right) == 2 && AVLEnabled)
if (toInsert < nodePtr->left->data)
rotateWithLeftChild(nodePtr);
else
doubleRotateWithLeftChild(nodePtr);
}
而且,这里是BST类确定指标
// BST class w/ templates
template <typename bstType>
class bst{
private: // private data members
// BST node structure (inline class)
class bstNode{
public: // public components in bstNode
// data members
bstType data;
bstNode* left;
bstNode* right;
// balancing information
int height;
// constructor
bstNode(bstType item){
left = NULL;
right = NULL;
data = item;
height = 0;
}
// destructor
// no special destructor is required for bstNode
};
// BST node pointer
typedef bstNode* bstNodePtr;
public: // public functions.....
什么可能会导致此任何想法的一部分?我是否重载错误的类或错误的函数?任何帮助表示赞赏 - 我似乎迷路了,因为很多不同的事情一次发生。
我道歉我之前的评论 - !你答案是正确的我最初误解了你的回答 – BSchlinker 2011-02-26 02:57:20