c++ - 将对象加载到指向对象的指针数组中

标签 c++ arrays class pointers

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

排序器.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;
}

排序器.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]);

最佳答案

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

关于c++ - 将对象加载到指向对象的指针数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17754743/

相关文章:

c++ - 使用 static_assert() 提供更好的编译时错误(比编译器)

c++ - C 程序中需要 LVALUE 作为赋值的左操作数

javascript - ng-repeat 基于第二个数组的长度的数组

Javascript:如何获取数组中特定顺序的值的索引?

c++ - 为什么用作嵌套成员的非模板类是不完整类型?

c++ - 仅剩余条目的 vector pop_back() 崩溃

c++ - 脚本语言和与 C API 的接口(interface)

Char* 从 char 数组中解析错误

javascript - 在 JavaScript 中,如何使用单个 ".prototype" block 从子类中继承父类?

java - 将 Java 对象的类型/类名称声明为字符串