我的程序是一个循环的6次迭代,其中有8个人互相投票。每个人在每次迭代期间投票的人都保存到私人班级成员voteList
(一个指针向量)。指向对象的指针的私有向量。如何使用getter方法访问这些对象?
我的麻烦是,在六次迭代结束时,我希望能够说出,例如,Anna在每次投票中投了谁,使用我写的GetVote(int)
公开方法。
*(voteList[round])
应该是Anna在给定回合投票的价值(一个人),我想呢?并且使用GetName()
方法应该检索该人员姓名的字符串。但无论我如何摆弄它,程序崩溃,只要我打电话GetVote()
。
我确定我犯了一个或多个真正愚蠢的错误,但我无法弄清楚问题所在。任何输入将不胜感激!
#include <iostream>
#include <vector>
#include <random>
#include <time.h>
using namespace std;
enum gender { male, female };
class Person {
private:
string personName;
gender personGender;
vector<Person *> voteList;
public:
// Constructors
Person (string, gender);
// Setters
void Vote (Person * target) {
voteList.push_back (target);
};
// Getters
string GetName() { return personName; };
string GetVote (int round)
{
Person ugh = *(voteList[round]);
return ugh.GetName();
};
};
Person::Person (string a, gender b) {
personName = a;
personGender = b; }
void Voting (vector<Person> voters)
{
for (int i = 0; i < voters.size(); i++) {
int number = (rand() % voters.size());
Person * myTarget = &voters[number];
voters[i].Vote (myTarget);
cout << voters[i].GetName() << " votes for " << voters[number].GetName() << endl;
}
cout << endl;
}
int main()
{
srand(time(0));
Person Anna ("Anna", female);
Person Baxter ("Baxter", male);
Person Caroline ("Caroline", female);
Person David ("David", male);
Person Erin ("Erin", female);
Person Frank ("Frank", male);
Person Gemma ("Gemma", female);
Person Hassan ("Hassan", male);
vector<Person> theGroup;
theGroup.push_back (Anna);
theGroup.push_back (Baxter);
theGroup.push_back (Caroline);
theGroup.push_back (David);
theGroup.push_back (Erin);
theGroup.push_back (Frank);
theGroup.push_back (Gemma);
theGroup.push_back (Hassan);
for (int n = 0, iterations = (theGroup.size() - 2); n <= iterations; n++)
Voting (theGroup);
cout << "ANNA VOTED FOR...";
for (int n = 0; n <= 5; n++)
{
cout << "Round " << (n + 1) << ": " << Anna.GetVote(n) << '\n';
}
cin.ignore();
return 0;
}
afaik std :: vector将分配堆上的对象,所以分配内存来存储指向另一个堆空间的指针是没有意义的。但无论如何...你的'GetVote(int)'成员需要一个检查,如果'round'小于或等于'voteList'对象的数量。其余部分由Nbr44解释;) – Zaiborg 2013-04-23 06:28:42