我的程序是一个循环的六次迭代,其中八个人互相投票。每个人在每次迭代中投票给谁被保存到私有类成员voteList
(指针向量)。
我的麻烦是,在六次迭代结束时,我希望能够使用GetVote(int)
我编写的 public 方法说,例如,Anna 在每次投票中投票给了谁。
*(voteList[round])
我认为应该是安娜在给定一轮中投票给谁的价值(一个人)?并且使用该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;
}