变量没有改变?通过向量的函数调用

variable has not changed? calling through function of a vector

本文关键字:向量 函数调用 改变 变量      更新时间:2023-10-16

这是我的代码,我已经做了多次测试,以确保将对象添加到向量中是正确的。所以我试着从那里再前进一点。我的程序是,选民类将有一个BallotPaper的向量,而BallotPaper。Candidate类将有一个名为_votecount的私有变量。

我想执行的是,我想使用函数Vote(int,int)通过Voter增加_votecount。

然而,在我的情况下,_votecount并没有像我预期的那样增加,我也没有弄清楚,这可能是显而易见的,因此我感谢任何输入。

这是我的主菜:

int main()
{
Date d1(2018, 10, 1);// new Date object
Member m1("Alice", 100, "Engineering", 012, d1, PositionType::Normal);
bool check = m1.CheckEligibility();
cout << check<<"n";
Voter v1("Ailee", 100, "Engineering", 012, d1, PositionType::Normal);
if (v1.getName() == "Ailee")
{
cout << "nTrue1n";   // Yes
}
BallotPaper bp1(PositionType::President);
v1.AddBallotPaper(bp1);
if (v1.getBallotPapers()[0].getPositionBP() == PositionType::President)
{
cout << "nTrue2n"; //Yes
}
Candidate c1("Ailee", 100, "Engineering", 012, d1, PositionType::Normal);
v1.getBallotPapers()[0].AddCandidate(c1);
if (v1.getBallotPapers()[0].getCandidates()[0].getName() == "Ailee")
{
cout << "nTrue3n";   //Yes
}
// Voter cast vote to increase candidate count
v1.Vote(0, 0);
if (c1.getVoteCount() == 1)
{
cout << "nDONEn";     //ERROR HERE!
}
return 0;
}

选民类别

class Voter :public Member
{
private:
std::vector<BallotPaper> _bp;  
public:
Voter::Voter(std::string a, int b, std::string c, int d, Date e, PositionType f) : Member(a, b, c, d, e, f) 
{}
void Voter::AddBallotPaper(BallotPaper b)
{
_bp.push_back(b);  
}
std::vector<BallotPaper>& Voter::getBallotPapers()
{
return this->_bp;
}
//HOW DO YOU VOTE?
void Voter::Vote(int paperindex,int index)
{
getBallotPapers()[paperindex].ChoiceVoted(index);   
}
}

BallotPaper类

class BallotPaper
{
private:
PositionType _positionbp;
std::vector<Candidate> _candidatesbp;   // only contain the required candidate
public:
BallotPaper::BallotPaper(PositionType a)
{
_positionbp = a;
}
std::vector<Candidate>& BallotPaper::getCandidates()
{
return this->_candidatesbp;
}
void BallotPaper::AddCandidate(Candidate c)
{
_candidatesbp.push_back(c);
}
void BallotPaper::ChoiceVoted(int index)
{
getCandidates()[index].IncreaseVoteCount();
}
}

候选类别

class Candidate :public Member
{
private:
int _votecount;
PositionType _position;
public:
void Candidate::IncreaseVoteCount()
{
_votecount++;
}
}

程序中创建的候选项将复制到Voter v中的矢量中。您应该使用v1.getBallotPapers()检查计数。

一个更简单的解决方案架构是将所有Candidate对象保持在向量中,而其他向量存储Candidate *,因此它们可以引用Candidate的单个定义。