逐步解說:偵錯專案 (C++)

在這個逐步解說中,您會修改程式以修正在測試專案時所發現的問題。

必要條件

修正具有 Bug 的程式

  1. 若要查看 Cardgame 物件被終結時發生什麼事,請檢視 Cardgame 類別的解構函式。

    在功能表列上,選擇 [檢視>類別檢視]。

    在 [類別檢視] 視窗中,展開 [Game] 專案樹狀結構並選取 [Cardgame] 類別來顯示類別成員和方法。

    開啟 ~Cardgame(void) 解構函式的捷徑功能表,然後選擇 [移至定義]

  2. 若要在 Cardgame 結束時減少 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鍵。

    請注意,在每個 Cardgame 建構函式執行後,totalParticipants 的值都會增加。 當 PlayGames 函式返回時,因為每個 Cardgame 執行個體會超出範圍而被刪除 (和呼叫解構函式),所以 totalParticipants 會減少。 就在執行 return 陳述式之前,totalParticipants 等於 0。

  7. 繼續逐步執行程式,直到程式結束,或選擇功能表列上的 [> 錯執行] 或選擇F5鍵來執行。

後續步驟

上一個主題:逐步解說:測試專案 (C++)
下一個主題:逐步解說:部署程式 (C++)

另請參閱

C++ 語言參考
專案與建置系統