0

我正在尝试将在 main 中创建的竞争对手对象(启动器)加载到一个排名对象,该对象将读入的竞争对手对象存储为一个指向读入对象的指针数组。由于某种原因,它只读取第一个对象传入。如何将主函数中的所有对象读取到类中的存储中?

ranker.cpp:

#include "ranker.h"
#include "competitor.h"
#include <stdlib.h>

Ranker::Ranker(int lanes) {
    athlete = new Competitor*[lanes];   // fix
    numAthletes = 0;
    maxAthletes = lanes;
}

int Ranker::addList(Competitor* starter) {
    if (numAthletes < maxAthletes && &starter != NULL) {
        athlete[numAthletes] = starter;
        numAthletes++;

        return numAthletes;
    }
    else
        return 0;
}

Competitor* Ranker::getLane(int lane) {
    for (int i = 0; i < numAthletes; i++) {
        if (athlete[i]->getLane() == lane - 1) {
            return athlete[i];
        }
    }
}

Competitor* Ranker::getFinish(int position) {
    switch(position) {
        case 1:
            return athlete[3];
            break;
        case 2:
            return athlete[2];
            break;
        case 3:
            return athlete[1];
            break;
        case 4:
            return athlete[0];
            break;
    }
}

int Ranker::getFilled() {
    return numAthletes;
}

Ranker::~Ranker() {
    delete athlete;
}

ranker.h:

#ifndef _RANKER_H
#define _RANKER_H

#include "competitor.h"

class Ranker {
private:
Competitor** athlete;
    int numAthletes;
    int maxAthletes;
public:
    Ranker(int lanes);
    int addList(Competitor* starter);
    Competitor* getLane(int lane);
    Competitor* getFinish(int position);
    int getFilled();
    ~Ranker();
};

#endif

主要功能的一部分:

for (int i = 0; i < lanes; i++)
    rank.addList(starters[i]);
4

1 回答 1

1

使用 astd::vector<Competitor>存储您的竞争对手,并使用 . 添加它们push_back()

于 2013-07-19T20:21:51.327 回答