gpt4 book ai didi

c++ - 如何通过模板调用运算符重载?

转载 作者:行者123 更新时间:2023-11-28 07:44:19 25 4
gpt4 key购买 nike

请看下面的代码

树.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) { ... }

关于c++ - 如何通过模板调用运算符重载?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15176084/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com