I'm trying to iterate through ArrayPlayers to find the oldest player. The logic would be to have a final pointer Player *Oldest to the oldest player. Here is my code:
#include <stdio.h>
#include <tchar.h>
#include <iostream>
using namespace std;
class Player {
int Age;
char *Name;
public:
Player() {}
void setName(char *n) {
Name = n;
}
void setAge(int a) {
Age = a;
}
bool operator > (Player &P) {
return Age > P.Age;
}
};
int main()
{
int NumPlayers;
cout << "How many persons do you want to enter?\n";
cin >> NumPlayers;
Player *ArrayPlayers = new Player[NumPlayers];
int age;
char *name = new char;
for (int i = 0; i < NumPlayers; i++) {
cout << "Enter player name: ";
cin >> name;
cout << "Enter player age: ";
cin >> age;
ArrayPlayers[i].setName(name);
ArrayPlayers[i].setAge(age);
}
//Find oldest player
Player *Current = ArrayPlayers[0];
Player *Previous = NULL;
Player *Oldest = NULL;
while (Current) {
if (!Previous) {
Oldest = Current;
Current = Current + 1;
} else {
//Make comparison using overloading operator >
if (Current > Oldest) {
Oldest = Current;
Current = Current + 1;
}
}
}
return 0;
}
What happens is that the following instruction is not permitted:
Player *Current = ArrayPlayers[0];
error C2440: 'initializing' : cannot convert from 'Player' to 'Player *'
Basically here I wanted to set a pointer to the first element of the array.
Can you point the reason for this error please? Do you see any other issues?
Thanks for your help.
new). Read up on "const correctness", as your comparison operator wants write-access to the involved operands. Check outstd::string.std::vector<Player>then you can usestd::max_elementstd::vector.char*for the string means that you have to manage the memory it is pointing to (which the code does not). Consider usingstd::stringinstead, which does that management for you.std::stringorstd::vectorthough.