Поделиться через


Walkthrough: Debugging a Project (C++)

In this step, you modify the program to fix the problem that was discovered when testing the project.

Prerequisites

This topic assumes that you understand the fundamentals of the C++ language.

To fix a program that has a bug

  1. To see what occurs when a Cardgame object is destroyed, view the destructor for the Cardgame class.

    If you are using Visual C++ Express 2010 with Basic Settings, choose Tools, Settings, Expert Settings.

    On the menu bar, choose View, Class View or click the Class View tab in the Solution Explorer window to see a representation of the class and its members. In the Class View window, expand the Game project tree and then choose the Cardgame class. The area underneath shows the class members and methods.

    Open the shortcut menu for the ~Cardgame(void) destructor and then choose Go To Definition.

  2. To decrease the totalParticipants value when a card game terminates, type the following code between the opening and closing braces of the Cardgame::~Cardgame destructor:

    totalParticipants -= players;
    cout << players << " players have finished their game.  There are now "
         << totalParticipants << " players in total." << endl;
    
  3. The Cardgame.cpp file should resemble this after your changes:

    #include "Cardgame.h"
    #include <iostream>
    
    using namespace std;
    
    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. On the menu bar, choose Build, Build Solution.

  5. On the menu bar, choose Debug, Start Debugging or choose the F5 key to run the program in Debug mode. The program pauses at the first breakpoint.

  6. On the menu bar, choose Debug, Step Over or choose the F10 key to step through the program.

    Note that after each Cardgame constructor executes, the value of totalParticipants increases. When the PlayGames function returns, as each Cardgame instance goes out of scope and the destructor is called, totalParticipants decreases.

  7. Just before the return statement is executed, totalParticipants equals 0. Continue stepping through the program until it exits, or on the menu bar, choose Debug, Continue, or choose the F5 key to allow the program to continue to run until it exits.

Next Steps

Previous: Walkthrough: Testing a Project (C++) | Next: Walkthrough: Deploying Your Program (C++)

See Also

Tasks

Visual C++ Guided Tour

Other Resources

Building and Debugging