【发布时间】:2013-04-16 06:03:04
【问题描述】:
我的程序是一个循环的六次迭代,其中八个人互相投票。每个人在每次迭代中投票给谁,保存到私有类成员voteList(指针向量)。
我的麻烦是,在六次迭代结束时,我希望能够使用我编写的GetVote(int) public 方法说,例如,安娜在每次投票中投票给了谁。
*(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 解释;)
标签: c++ pointers methods vector getter