变量没有改变?通过向量的函数调用
variable has not changed? calling through function of a vector
这是我的代码,我已经做了多次测试,以确保将对象添加到向量中是正确的。所以我试着从那里再前进一点。我的程序是,选民类将有一个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
的单个定义。
相关文章:
- 变量没有改变?通过向量的函数调用
- 在具有向量的类构造函数中进行析构函数调用
- 有没有一种简单的方法可以在对象向量上调用构造函数?
- 防止我的向量在调用它的函数结束时被删除
- 析构函数调用c++中的一个向量
- 具有多线程支持的 RenderClass,将函数调用推送到向量以在另一个线程上调用
- 在使用标准向量函数时引发'std::bad_alloc'实例后调用的终止
- 用构造函数调用填充向量
- 如何在另一个类的向量中调用派生类的析构函数
- 如何在 std::future 的向量中调用异步函数
- 仅在删除包含对象的向量时调用自定义»析构函数«
- 为什么连续的向量:: push_back将导致不同数量的构造函数调用
- 无法在对象的向量中调用函数
- 有没有办法<int><double>在使用 C++11 函数调用期间自动将"向量"提升为"向量"?
- C 关于将数组复制到向量并调用其变量 /函数
- c++oop初学者-在一个函数调用中返回向量中每个创建对象的输出和
- 使用派生类的向量映射调用其类的函数
- 直接在函数调用的参数列表中初始化向量
- Visual Studio报告对结构向量的push_back()函数调用出错
- C++从函数调用的多个返回中构建字符串向量的最佳方法