【问题标题】:C++ STD::List: Trouble Iterating Through ListC++ STD::List:遍历列表时遇到问题
【发布时间】:2020-11-07 14:53:46
【问题描述】:

运行我的代码时,它编译得很好,但我不明白为什么它没有迭代并打印出我的列表。

我有一个子类 Games 和超类:play_ballstatistics

目标是让玩家玩游戏,跟踪他们需要多少次尝试才能获胜。在每次播放结束时,它会跟踪每次播放的统计信息,并将其推送到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);

【问题讨论】:

标签: c++ list loops inheritance iterator


【解决方案1】:

参数“sts”是按值而不是按引用传递的。当通过引用传递参数时,调用者和被调用者使用相同的变量作为参数。如果被调用者修改了参数变量,效果对调用者的变量是可见的。当参数传值时,调用者和被调用者有两个具有相同值的自变量。如果被调用者修改了参数变量,则调用者看不到效果。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多