演练:调试项目 (C++)

在本步骤中,您将调整程序以修复在测试项目时你所发现的问题。

系统必备

修复包含 bug 的程序

  1. 要理解在撤销 Cardgame 对象时会发生什么, 请查看 Cardgame 类的析构函数。

    在菜单栏上,选择“查看” 、“类似图” 。

    在“类视图” 窗口中,展开“游戏” 项目树并选择“Cardgame” 类展示类成员和方法。

    打开 ~Cardgame (失效) 析构函数的快捷菜单然后选择“转到定义” 。

  2. 在卡片游戏终止时 totalParticipants会递减,请在析构函数 Cardgame::~Cardgame 的左大括号和右大括号之间加入以下代码:

    totalParticipants -= players;
    cout << players << " players have finished their game.  There are now "
         << totalParticipants << " players in total." << endl;
    
  3. 在您对 Cardgame.cpp 文件进行更改之后,该文件应类似于:

    #include "Cardgame.h"
    #include <iostream>
    
    using namespace std;
    
    int Cardgame::totalParticipants = 0;
    
    Cardgame::Cardgame(int players)
        : players(players)
    {
        totalParticipants += players;
        cout << players << " players have started a new game.  There are now "
             << totalParticipants << " players in total." << endl;
    }
    
    Cardgame::~Cardgame()
    {
        totalParticipants -= players;
        cout << players << " players have finished their game.  There are now "
             << totalParticipants << " players in total." << endl;
    }
    
  4. 在菜单栏上,依次选择**“生成”“生成解决方案”**。

  5. 在版本完成后,通过选择在菜单栏上的“调试” “启动调试” 运行调试模式,或按 F5 键。程序将在第一个断点处暂停。

  6. 若要逐句通过程序单步执行,则在菜单栏上,选择“调试” ,“单步执行” ,或选择 F10 键。

    请注意,当卡片游戏的每个构造函数都执行后,totalParticipants 的值会增大。当 PlayGames 函数返回,由于每个超出范围的卡片游戏实例都将被删除 (并调用析构函数),totalParticipants 降低。恰好在执行 return 语句之前,totalParticipants 等于 0。

  7. 继续逐句执行程序,直到退出或让其通过选择在菜单栏上的“调试” ,“运行” ,或通过选择 F5 键运行。

后续步骤

上一部分:演练:测试项目 (C++) | 下一部分:演练:部署程序 (C++)

请参见

任务

Visual C++ 指导教程

其他资源

Building, Debugging, and Testing