2013-03-02 65 views
0

请看看下面的代码如何通过模板调用运算符重载?

tree.h中

//Tree Data Structure. 

    #pragma once 
    #include <iostream> 
    #include "Player.h" 
    template <typename T> 

    class Tree 
    { 
    public: 
     T* root; 

    Tree(void) 
    { 
     root = 0; 
    } 


    Tree::~Tree(void) 
    { 
    } 

    //Find elements in tree (Find() function removed) 


    //Display values in tree (Display() Function removed) 

    //Insert data into tree 
    void Insert(T * data) 
    { 
     T *newNode = data; 

     if(this->root == 0) 
     { 
      root = newNode; 
     } 
     else 
     { 
      T *current = root; 
      T *parent; 

      while(true) 
      { 
       parent = current; 

       if(data->id < current->id) 
       { 
        current = current->leftChild; 

        if(current==0) 
        { 
         parent->leftChild = newNode; 
         return; 
        } 
       } 
       else 
       { 
        current = current->rightChild; 

        if(current==0) 
        { 
         parent->rightChild = newNode; 
         return; 
        } 
       } 
      } 
     } 
    } 
    }; 

Player.h

#pragma once 
#include "GameObject.h" 
#include "Tree.h" 

class Player:public GameObject 
{ 
public: 
    Player(void); 
    ~Player(void); 

    Player *rightChild; 
    Player *leftChild; 

    void Display(); 
    bool operator !=(const Player&); 
    bool operator <(const Player&); 

}; 

Player.cpp

#include "Player.h" 
#include <iostream> 

Player::Player(void) 
{ 
    leftChild = 0; 
    rightChild = 0; 
} 


Player::~Player(void) 
{ 
} 



bool Player::operator!=(const Player& player) 
{ 
    if(instances==NULL) 
    { 
     return false; 
    } 
    else 
    { 
     return true; 
    } 
} 

bool Player::operator<(const Player& player) 
{ 

    if(this->instances < player.instances) 
    { 
     return true; 
    } 
    else 
    { 
     return false; 
    } 
} 

在这里,Tree是一个模板。 Player类是将被插入到树中的类。

Tree.h,里面的Insert()方法,而不是if(data->id < current->id)我需要调用播放器的<重载操作符。我怎样才能做到这一点?请帮忙!

回答

1

你可以解引用您的指针,就像这样:

if (*data < *current) { ... } 
+0

哇哇哇!谢谢!! – 2013-03-02 15:31:20