如何通过模板调用操作符重载



请看下面的代码

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),我需要调用玩家的<重载操作符。我该怎么做呢?请帮助!

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

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

最新更新