这是我的代码,我进行了多次测试以确保将对象添加到 vector 中是正确的。所以我试着从那里再前进一点。 我的程序是 Voter 类将有一个 BallotPaper vector ,而 BallotPaper 将有一个 Candidate vector 。 Candidate 类将有一个名为_votecount 的私有(private)变量。
我想要执行的是,我想通过 Voter 增加 _votecount,使用函数 Vote(int,int)
。
但是在我的例子中,_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 << "\nTrue1\n"; // Yes
}
BallotPaper bp1(PositionType::President);
v1.AddBallotPaper(bp1);
if (v1.getBallotPapers()[0].getPositionBP() == PositionType::President)
{
cout << "\nTrue2\n"; //Yes
}
Candidate c1("Ailee", 100, "Engineering", 012, d1, PositionType::Normal);
v1.getBallotPapers()[0].AddCandidate(c1);
if (v1.getBallotPapers()[0].getCandidates()[0].getName() == "Ailee")
{
cout << "\nTrue3\n"; //Yes
}
// Voter cast vote to increase candidate count
v1.Vote(0, 0);
if (c1.getVoteCount() == 1)
{
cout << "\nDONE\n"; //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
中的 vector 中。您应该使用 v1.getBallotPapers()
检查计数。
一个更简单的解决方案架构是将所有 Candidate
对象保存在一个 vector 中,而其他 vector 存储 Candidate *
,因此它们可以引用Candidate
的单一定义。
关于c++ - 变量没变?通过 vector 函数调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53130706/