【发布时间】:2020-11-07 14:53:46
【问题描述】:
运行我的代码时,它编译得很好,但我不明白为什么它没有迭代并打印出我的列表。
我有一个子类 Games 和超类:play_ball 和 statistics。
目标是让玩家玩游戏,跟踪他们需要多少次尝试才能获胜。在每次播放结束时,它会跟踪每次播放的统计信息,并将其推送到stats列表的末尾。
我想我已经为它设置好了所有东西,但是当我去打印统计数据时,它甚至不会遍历列表的任何部分。
我在main.cpp 中初始化我的列表,并将统计信息推送到play_ball 类中play() 函数的末尾。
是否在每场比赛结束时由于某种原因没有填写列表?如果是这样,我该如何解决这个问题?
这是我的代码:
games.h:
class games {
friend class statistics;
friend class play_ball;
private:
std::string type;
int attempts = 0;
public:
games();
~games();
virtual void play(std::list<stats>) = 0;
};
static int plays = 0;
play_ball.cpp:
void stats::play(std::list<stats> sts)
{
// Plays the game...
sts.push_back(stats(get_plays(), "Ball ", count));
}
stats.cpp
void stats::play(std::list<stats> sts)
{
if (get_plays() == 0)
{
printf("ERROR: No game history.\n");
}
else
{
std::cout << "[Game Type Attempts:]\n";
// This should go through and print out: [game number] Ball (# of attempts)
// but when I run it, it just skips the loop and prints the "Thanks for playing!"
for (std::list<stats>::iterator p = sts.begin(); p != sts.end(); ++p)
{
std::cout << '[' << (*p).get_plays() << "] "<< (*p).get_type(sts) << " "<< (*p).get_atmpts(sts) << '\n';
}
std::cout << "Thanks for playing!";
}
}
main.cpp:
stats sts;
std::list<stats> l_sts;
play_ball ball;
ball.play(l_sts);
sts.play(l_sts);
【问题讨论】:
-
阅读the difference between pass by value and pass by reference。
void stats::play(std::list<stats> sts)按值传递,因此函数内部执行的工作是在副本上,而不是在原始上。请改用void stats::play(std::list<stats> &sts)。
标签: c++ list loops inheritance iterator