0
我試圖加載競爭對象(啓動器)在主要創建一個排序器對象,存儲競爭對手的讀取作爲讀入對象的指針數組中的對象。由於某種原因,它只讀取傳入的第一個對象。如何將主函數中的所有對象讀入類中的存儲?將對象加載到指向對象的指針陣列
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]);
你的第一個問題是你使用指針,你的第二個問題也是使用指針。瞭解有關C++ [標準容器](http://en.cppreference.com/w/cpp/container)的更多信息。 –