在C ++中迭代对象数组

时间:2015-01-24 19:25:04

标签: c++ arrays

我试图通过ArrayPlayers迭代找到最老的玩家。逻辑是给最老的玩家一个最终指针Player *Oldest。这是我的代码:

#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;
}

不允许以下说明:

Player *Current = ArrayPlayers[0];

error C2440: 'initializing' : cannot convert from 'Player' to 'Player *'

基本上我想在这里设置一个指向数组第一个元素的指针。

你能指出这个错误的原因吗?你还有其他问题吗?

感谢您的帮助。

1 个答案:

答案 0 :(得分:2)

替换

Player *Current = ArrayPlayers[0];

Player *Current = &ArrayPlayers[0];

如果不是拼写错误(我不相信,因为错误信息非常有用) 考虑阅读this