在 C++ 中建立主控台計算機Create a console calculator in C++

通常 C++ 程式設計師的起點都是 "Hello, world!"The usual starting point for a C++ programmer is a "Hello, world!" 應用程式 (在命令列上執行)。application that runs on the command line. 這就是您將在本文的 Visual Studio 中先建立的內容,然後我們會繼續進行更具挑戰性的作業:計算機應用程式。That's what you'll create first in Visual Studio in this article, and then we'll move on to something more challenging: a calculator app.

必要條件Prerequisites

  • 已在您的電腦上安裝並執行使用 c + + 的桌面開發工作負載 Visual Studio。Have Visual Studio with the Desktop development with C++ workload installed and running on your computer. 若尚未安裝,請參閱 Install C++ support in Visual Studio (在 Visual Studio 中安裝 C++ 支援)。If it's not installed yet, see Install C++ support in Visual Studio.

建立您的應用程式專案Create your app project

Visual Studio 會使用「專案」** 來組織應用程式的程式碼,並使用「解決方案」** 來組織專案。Visual Studio uses projects to organize the code for an app, and solutions to organize your projects. 專案包含用來建置您應用程式的所有選項、組態和規則。A project contains all the options, configurations, and rules used to build your apps. 它也會管理所有專案之檔案與任何外部檔案間的關聯性。It also manages the relationship between all the project's files and any external files. 若要建立您的應用程式,首先,您會建立新的專案及解決方案。To create your app, first, you'll create a new project and solution.

  1. 如果您剛開始使用 Visual Studio,會看到 [Visual Studio 2019] 對話方塊。If you've just started Visual Studio, you'll see the Visual Studio 2019 dialog box. 選擇 [建立新專案]**** 以開始使用。Choose Create a new project to get started.

    Visual Studio 2019 初始對話方塊The Visual Studio 2019 initial dialog

    否則,請在 Visual Studio 的功能表列上 ,選擇 [ 檔案] [新增] [ > New > 專案]。Otherwise, on the menubar in Visual Studio, choose File > New > Project. [建立新專案]**** 視窗會隨即開啟。The Create a new project window opens.

  2. 在專案範本清單中,選擇 [主控台應用程式]****,然後選擇 [下一步]****。In the list of project templates, choose Console App, then choose Next.

    選擇 [主控台應用程式] 範本Choose the Console App template

    重要

    請務必選擇 C++ 版本的主控台應用程式範本。Make sure you choose the C++ version of the Console App template. 它有 C++WindowsConsole 標籤,角落有 "++" 圖示。It has the C++, Windows, and Console tags, and the icon has "++" in the corner.

  3. 在 [設定新專案]**** 對話方塊中,選取 [專案名稱]**** 編輯方塊中,將您的新專案命名為 CalculatorTutorial,然後選擇 [建立]****.In the Configure your new project dialog box, select the Project name edit box, name your new project CalculatorTutorial, then choose Create.

    在 [設定您的新專案] 對話方塊中,為您的專案命名Name your project in the Configure your new project dialog

    會建立空白的 C++ Windows 主控台應用程式。An empty C++ Windows console application gets created. 主控台應用程式會使用 Windows 主控台視窗來顯示輸出並接受使用者輸入。Console applications use a Windows console window to display output and accept user input. 在 Visual Studio 中,一個編輯器視窗隨即開啟,並顯示產生的程式碼:In Visual Studio, an editor window opens and shows the generated code:

    // CalculatorTutorial.cpp : This file contains the 'main' function. Program execution begins and ends there.
    //
    
    #include <iostream>
    
    int main()
    {
        std::cout << "Hello World!\n";
    }
    
    // Run program: Ctrl + F5 or Debug > Start Without Debugging menu
    // Debug program: F5 or Debug > Start Debugging menu
    
    // Tips for Getting Started:
    //   1. Use the Solution Explorer window to add/manage files
    //   2. Use the Team Explorer window to connect to source control
    //   3. Use the Output window to see build output and other messages
    //   4. Use the Error List window to view errors
    //   5. Go to Project > Add New Item to create new code files, or Project > Add Existing Item to add existing code files to the project
    //   6. In the future, to open this project again, go to File > Open > Project and select the .sln file
    

驗證您新的應用程式可以建置及執行Verify that your new app builds and runs

新 Windows 主控台應用程式範本會建立簡易的 C++ "Hello World" 應用程式。The template for a new Windows console application creates a simple C++ "Hello World" app. 此時,您會看到 Visual Studio 如何直接從 IDE 建置及執行您建立的應用程式。At this point, you can see how Visual Studio builds and runs the apps you create right from the IDE.

  1. 若要建置您的專案,請從 [建置]**** 功能表中選擇 [建置方案]****。To build your project, choose Build Solution from the Build menu. [輸出]**** 視窗會顯示建置過程的結果。The Output window shows the results of the build process.

    建立專案Build the project

  2. 若要執行程式碼,請在功能表列上,選擇 [偵錯]****、[啟動但不偵錯]****。To run the code, on the menu bar, choose Debug, Start without debugging.

    啟動專案Start the project

    主控台視窗會隨即開啟並執行您的應用程式。A console window opens and then runs your app. 當您在 Visual Studio 中啟動主控台應用程式時,它會執行您的程式碼,然後印出「按任意鍵即可關閉此視窗」。When you start a console app in Visual Studio, it runs your code, then prints "Press any key to close this window . .. ."." 讓您可以有機會查看輸出。to give you a chance to see the output. 恭喜!Congratulations! 您已在 Visual Studio 中建立了您的第一個 "Hello, world!"You've created your first "Hello, world!" 主控台應用程式!console app in Visual Studio!

  3. 請按任意鍵關閉主控台視窗並返回 Visual Studio。Press a key to dismiss the console window and return to Visual Studio.

您現在已具備了在每一項變更之後建置及執行您應用程式的工具,可驗證程式碼仍依照您預期的方式運作。You now have the tools to build and run your app after every change, to verify that the code still works as you expect. 稍後,我們將示範如何在無法正常運作時進行偵錯。Later, we'll show you how to debug it if it doesn't.

編輯程式碼Edit the code

現在,讓我們將此範本中的程式碼轉換成計算機應用程式。Now let's turn the code in this template into a calculator app.

  1. CalculatorTutorial.cpp 檔案中,編輯程式碼,使其與此範例相符:In the CalculatorTutorial.cpp file, edit the code to match this example:

    // CalculatorTutorial.cpp : This file contains the 'main' function. Program execution begins and ends there.
    //
    
    #include <iostream>
    
    using namespace std;
    
    int main()
    {
        cout << "Calculator Console Application" << endl << endl;
        cout << "Please enter the operation to perform. Format: a+b | a-b | a*b | a/b"
            << endl;
        return 0;
    }
    
    // Run program: Ctrl + F5 or Debug > Start Without Debugging menu
    // Debug program: F5 or Debug > Start Debugging menu
    // Tips for Getting Started:
    //   1. Use the Solution Explorer window to add/manage files
    //   2. Use the Team Explorer window to connect to source control
    //   3. Use the Output window to see build output and other messages
    //   4. Use the Error List window to view errors
    //   5. Go to Project > Add New Item to create new code files, or Project > Add Existing Item to add existing code files to the project
    //   6. In the future, to open this project again, go to File > Open > Project and select the .sln file
    

    了解程式碼:Understanding the code:

    • #include 陳述式可讓您參考位於其他檔案中的程式碼。The #include statements allow you to reference code located in other files. 有時候,您可能會看到以角括弧()括住的檔案名 <> ; 其他時間則是以引號("")括住。Sometimes, you may see a filename surrounded by angle brackets (<>); other times, it's surrounded by quotes (" "). 一般情況下,角括弧會在參考 C++ 標準程式庫時使用,引號則用於其他檔案。In general, angle brackets are used when referencing the C++ Standard Library, while quotes are used for other files.
    • using namespace std; 這一行則會告知編譯器,預期在此檔案中使用來自 C++ 標準程式庫的功能。The using namespace std; line tells the compiler to expect stuff from the C++ Standard Library to be used in this file. 若沒有這一行,每個來自程式庫的關鍵字都必須在開頭加上 std:: 以表示其範圍。Without this line, each keyword from the library would have to be preceded with a std::, to denote its scope. 例如,若沒有該行,每個對 cout 的參考都必須寫成 std::coutFor instance, without that line, each reference to cout would have to be written as std::cout. using 已加入語句,讓程式碼看起來更清楚。The using statement is added to make the code look more clean.
    • cout 關鍵字則用於印出至 C++ 中的標準輸出。The cout keyword is used to print to standard output in C++. << 運算子會指示編譯器將其右邊的任何內容傳送至標準輸出。The << operator tells the compiler to send whatever is to the right of it to the standard output.
    • endl 關鍵字則像是 Enter 鍵,它會結束這一行並將游標移到下一行。The endl keyword is like the Enter key; it ends the line and moves the cursor to the next line. \n 放在字串內部 (即包含在 "" 中) 以進行相同操作是較佳的做法,因為 endl 會排清緩衝區而可能影響程式的效能,但由於這個應用程式很小,所以我們在此處使用 endl 來改善可讀性。It is a better practice to put a \n inside the string (contained by "") to do the same thing, as endl always flushes the buffer and can hurt the performance of the program, but since this is a very small app, endl is used instead for better readability.
    • 所有 C++ 陳述式都必須以分號結尾,且所有的 C++ 應用程式都必須包含一個 main() 函式。All C++ statements must end with semicolons and all C++ applications must contain a main() function. 此函式是程式在開始時執行的部分。This function is what the program runs at the start. 所有程式碼都必須要能夠從 main() 存取,才能使用。All code must be accessible from main() in order to be used.
  2. 若要儲存檔案,請按下 Ctrl+S,或選擇靠近 IDE 頂端的儲存圖示,即功能表列下方工具列中的磁碟片圖示。To save the file, enter Ctrl+S, or choose the Save icon near the top of the IDE, the floppy disk icon in the toolbar under the menu bar.

  3. 若要執行應用程式,請按下 Ctrl+F5,或前往 [偵錯]**** 功能表,然後選擇 [啟動但不偵錯]****。To run the application, press Ctrl+F5 or go to the Debug menu and choose Start Without Debugging. 您應該會看到一個主控台視窗出現,它顯示程式碼中指定的文字。You should see a console window appear that displays the text specified in the code.

  4. 當您完成時,請關閉主控台視窗。Close the console window when you're done.

新增程式碼來執行數學運算Add code to do some math

是時候新增一些數學邏輯了。It's time to add some math logic.

新增 Calculator 類別To add a Calculator class

  1. 前往 [專案]**** 功能表,然後選擇 [新增類別]****。Go to the Project menu and choose Add Class. 在 [類別名稱]**** 編輯方塊中,輸入 CalculatorIn the Class Name edit box, enter Calculator. 選擇 [確定]。Choose OK. 會將兩個新檔案新增到您的專案。Two new files get added to your project. 若要一次儲存您所有變更的檔案,請按 Ctrl+Shift+STo save all your changed files at once, press Ctrl+Shift+S. 這是 [檔案] [ File > 全部儲存] 的鍵盤快速鍵。It's a keyboard shortcut for File > Save All. [全部儲存]**** 也有一個工具列按鈕,即兩個磁碟片的圖示,您可在 [儲存]**** 按鈕的旁邊找到。There's also a toolbar button for Save All, an icon of two floppy disks, found beside the Save button. 一般情況下,頻繁地進行 [全部儲存]**** 是良好的做法,因為這樣可避免您在儲存時遺漏任何檔案。In general, it's good practice to do Save All frequently, so you don't miss any files when you save.

    建立計算機類別Create the Calculator class

    類別就像是物件的藍圖,可進行某些操作。A class is like a blueprint for an object that does something. 在此案例中,我們會定義一個計算機及其運作的方式。In this case, we define a calculator and how it should work. 您在上方使用的 [新增類別精靈]**** 會建立 .h 及 .cpp 檔案,且其名稱和類別皆相同。The Add Class wizard you used above created .h and .cpp files that have the same name as the class. 您可以在 [方案總管] 視窗中看到專案檔案的完整清單,在 IDE 的側邊看到。You can see a full list of your project files in the Solution Explorer window, visible on the side of the IDE. 如果看不到視窗,您可以從功能表列開啟它:選擇 [ View > 方案總管]。If the window isn't visible, you can open it from the menu bar: choose View > Solution Explorer.

    方案總管Solution Explorer

    您現在應該會在編輯器中開啟三個索引標籤: calculatortutorial.cpp .cpp計算機 .h計算機 .cppYou should now have three tabs open in the editor: CalculatorTutorial.cpp, Calculator.h, and Calculator.cpp. 如果您不小心關閉其中一個,您可以在 [方案總管] 視窗中按兩下它來重新開啟。If you accidentally close one of them, you can reopen it by double-clicking it in the Solution Explorer window.

  2. Calculator.h 中,移除所產生的 Calculator();~Calculator(); 這兩行,因為您在此處不需要它們。In Calculator.h, remove the Calculator(); and ~Calculator(); lines that were generated, since you won't need them here. 接下來,請新增下列這行程式碼,使其看起來與下列內容相似:Next, add the following line of code so the file now looks like this:

    #pragma once
    class Calculator
    {
    public:
        double Calculate(double x, char oper, double y);
    };
    

    了解程式碼Understanding the code

    • 您新增的這一行會宣告一個稱為 Calculate 的新函式,我們會使用此函式來進行數學運算,包含加、減、乘及除。The line you added declares a new function called Calculate, which we'll use to run math operations for addition, subtraction, multiplication, and division.
    • C++ 程式碼會整理成「標頭」(.h) 檔案及「來源」(.cpp) 檔案。C++ code is organized into header (.h) files and source (.cpp) files. 各種編譯器還支援數種其他副檔名,但這些是您需了解的主要項目。Several other file extensions are supported by various compilers, but these are the main ones to know about. 函式和變數通常會經過「宣告」,即在標頭檔中提供名稱和型別,然後在來源檔案中「實作」(或提供定義)。Functions and variables are normally declared, that is, given a name and a type, in header files, and implemented, or given a definition, in source files. 若要存取另一個檔案中定義的程式碼,您可以使用 #include "filename.h",其中 'filename.h' 是宣告您欲使用變數或函式的檔案名稱。To access code defined in another file, you can use #include "filename.h", where 'filename.h' is the name of the file that declares the variables or functions you want to use.
    • 您刪除之兩行會宣告類別的「建構函式」** 及「解構函式」**。The two lines you deleted declared a constructor and destructor for the class. 針對如此範例的簡單類別,編譯器會為您建立它們,且其使用用途也不在本教學課程的範圍內。For a simple class like this one, the compiler creates them for you, and their uses are beyond the scope of this tutorial.
    • 將您的程式碼根據其用途整理成不同檔案是一種良好做法,因為這可讓您在稍後需要的時候輕易地尋找它們。It's good practice to organize your code into different files based on what it does, so it's easy to find the code you need later. 在我們的案例中,我們將 Calculator 類別與包含 main() 函式的檔案分開來定義,但我們計劃在 main() 中參考 Calculator 類別。In our case, we define the Calculator class separately from the file containing the main() function, but we plan to reference the Calculator class in main().
  3. 您會在 Calculate 的下方看到綠色的彎曲箭號。You'll see a green squiggle appear under Calculate. 這是因為我們尚未在 .cpp 檔案中定義 Calculate 函式。It's because we haven't defined the Calculate function in the .cpp file. 暫留在文字上,按一下彈出的燈泡 (在此例中是螺絲起子),然後選擇 [在 Calculator.cpp 中建立 'Calculate' 的定義]****。Hover over the word, click the lightbulb (in this case, a screwdriver) that pops up, and choose Create definition of 'Calculate' in Calculator.cpp.

    建立計算的定義Create definition of Calculate

    快顯視窗隨即出現,可讓您預覽在其他檔案中進行的程式碼變更。A pop-up appears that gives you a peek of the code change that was made in the other file. 程式碼已新增至 Calculator.cppThe code was added to Calculator.cpp.

    具有 [計算] 定義的快顯視窗Pop-up with definition of Calculate

    目前,它只會傳回 0.0。Currently, it just returns 0.0. 讓我們改變這點。Let's change that. Esc 來關閉快顯視窗。Press Esc to close the pop-up.

  4. 在編輯器視窗中切換至 Calculator.cpp 檔案。Switch to the Calculator.cpp file in the editor window. 移除 Calculator()~Calculator() 這兩個區段 (如同您在 .h 檔案中所進行的操作),並將下列程式碼新增至 Calculate()Remove the Calculator() and ~Calculator() sections (as you did in the .h file) and add the following code to Calculate():

    #include "Calculator.h"
    
    double Calculator::Calculate(double x, char oper, double y)
    {
        switch(oper)
        {
            case '+':
                return x + y;
            case '-':
                return x - y;
            case '*':
                return x * y;
            case '/':
                return x / y;
            default:
                return 0.0;
        }
    }
    

    了解程式碼Understanding the code

    • Calculate 函式會取用一個數字、一個運算子及第二個數字,然後在數字上執行所要求的運算。The function Calculate consumes a number, an operator, and a second number, then performs the requested operation on the numbers.
    • Switch 陳述式會檢查提供的運算子為何,並只執行對應至該運算的案例。The switch statement checks which operator was provided, and only executes the case corresponding to that operation. default: 案例是一種後援案例,若使用者鍵入不接受的運算子,即會使用此案例以避免中斷程式。The default: case is a fallback in case the user types an operator that isn't accepted, so the program doesn't break. 一般情況下,使用更簡潔的方式處理無效使用者輸入會是最佳做法,但這不在本教學課程的範圍內。In general, it's best to handle invalid user input in a more elegant way, but this is beyond the scope of this tutorial.
    • double 關鍵字代表支援小數的數位類型。The double keyword denotes a type of number that supports decimals. 如此一來,計算機便能夠同時處理小數點及整數的數學運算。This way, the calculator can handle both decimal math and integer math. 函式 Calculate 必須一律傳回這類數位,因為程式碼的 double 開頭是(這表示函式的傳回型別),這就是為什麼我們會傳回0.0,即使是在預設情況下也是如此。The Calculate function is required to always return such a number due to the double at the very start of the code (this denotes the function's return type), which is why we return 0.0 even in the default case.
    • .h 檔案會宣告函式的「原型」**,預先告知編譯器其需要的參數,以及該預期的傳回型別為何。The .h file declares the function prototype, which tells the compiler upfront what parameters it requires, and what return type to expect from it. .cpp 檔案則包含函式所有的實作詳細資料。The .cpp file has all the implementation details of the function.

如果您此時再次建置並執行程式碼,其仍會在詢問要執行哪項作業後結束。If you build and run the code again at this point, it will still exit after asking which operation to perform. 接下來,您會修改 main 函式來進行一些運算。Next, you'll modify the main function to do some calculations.

呼叫 Calculator 類別成員函式To call the Calculator class member functions

  1. 現在讓我們來更新 CalculatorTutorial.cpp 中的 main 函式:Now let's update the main function in CalculatorTutorial.cpp:

    // CalculatorTutorial.cpp : This file contains the 'main' function. Program execution begins and ends there.
    //
    
    #include <iostream>
    #include "Calculator.h"
    
    using namespace std;
    
    int main()
    {
        double x = 0.0;
        double y = 0.0;
        double result = 0.0;
        char oper = '+';
    
        cout << "Calculator Console Application" << endl << endl;
        cout << "Please enter the operation to perform. Format: a+b | a-b | a*b | a/b"
             << endl;
    
        Calculator c;
        while (true)
        {
            cin >> x >> oper >> y;
            result = c.Calculate(x, oper, y);
            cout << "Result is: " << result << endl;
        }
    
        return 0;
    }
    

    了解程式碼Understanding the code

    • 由於 C++ 程式一律會從 main() 函式開始,而我們需要從該處呼叫我們的其他程式碼,因此需要 #include 陳述式。Since C++ programs always start at the main() function, we need to call our other code from there, so a #include statement is needed.
    • 我們宣告了某些初始變數 xyoperresult,分別用來儲存第一個數字、第二個數字、運算子及最終結果。Some initial variables x, y, oper, and result are declared to store the first number, second number, operator, and final result, respectively. 提供它們某些初始值以避免未定義的行為是一種良好做法,而我們也在此處進行了這項操作。It is always good practice to give them some initial values to avoid undefined behavior, which is what is done here.
    • Calculator c; 這一行會宣告一個名為 'c' 的物件,作為 Calculator 類別的執行個體。The Calculator c; line declares an object named 'c' as an instance of the Calculator class. 類別本身只是計算機運作的藍圖;物件則是進行數學運算的特定計算機。The class itself is just a blueprint for how calculators work; the object is the specific calculator that does the math.
    • while (true) 陳述式是一種迴圈。The while (true) statement is a loop. 只要 () 內的條件為 True,迴圈內的程式碼就會繼續重複執行。The code inside the loop continues to execute over and over again as long as the condition inside the () holds true. 因為此條件只會列為 true ,所以一律為 true,因此迴圈會永遠執行。Since the condition is simply listed as true, it's always true, so the loop runs forever. 若要關閉程式,使用者必須手動關閉主控台視窗。To close the program, the user must manually close the console window. 否則,程式一律都會等待新的輸入。Otherwise, the program always waits for new input.
    • cin 關鍵字則用於接受使用者的輸入。The cin keyword is used to accept input from the user. 假設使用者輸入符合必要規格,輸入串流便能處理在主控台視窗中輸入的文字行,並依序將它放在每個列出的變數內。This input stream is smart enough to process a line of text entered in the console window and place it inside each of the variables listed, in order, assuming the user input matches the required specification. 您可以修改此行來接受不同類型的輸入 (例如兩個以上的數字),雖然 Calculate() 函式也需要更新才能進行處理。You can modify this line to accept different types of input, for instance, more than two numbers, though the Calculate() function would also need to be updated to handle this.
    • c.Calculate(x, oper, y); 運算式會呼叫先前定義的 Calculate 函式,並提供輸入的輸入值。The c.Calculate(x, oper, y); expression calls the Calculate function defined earlier, and supplies the entered input values. 函式接著會傳回儲存在 result 中的數字。The function then returns a number that gets stored in result.
    • 最後,result 會印出到主控台,讓使用者看見運算的結果。Finally, result is printed to the console, so the user sees the result of the calculation.

再次建置並測試程式碼Build and test the code again

現在,是時候再次測試程式以確認所有功能皆正常運作了。Now it's time to test the program again to make sure everything works properly.

  1. 請按 Ctrl+F5 來重新建置並啟動應用程式。Press Ctrl+F5 to rebuild and start the app.

  2. 輸入 5 + 5 ,然後按enter鍵。Enter 5 + 5, and press Enter. 驗證結果為 10。Verify that the result is 10.

    5 + 5 的結果The result of 5 + 5

偵錯應用程式Debug the app

因為使用者可以在主控台視窗中鍵入任何內容,讓我們確認計算機能依照預期的方式處理某些輸入。Since the user is free to type anything into the console window, let's make sure the calculator handles some input as expected. 相較於執行程式,我們可以改為針對它進行偵錯,讓我們可以詳細地逐步檢查其進行的作業。Instead of running the program, let's debug it instead, so we can inspect what it's doing in detail, step-by-step.

在偵錯工具中執行應用程式To run the app in the debugger

  1. result = c.Calculate(x, oper, y); 這一行設定中斷點,即在向使用者要求輸入之後。Set a breakpoint on the result = c.Calculate(x, oper, y); line, just after the user was asked for input. 若要設定中斷點,請按一下編輯器視窗左邊緣灰色垂直列中的行。To set the breakpoint, click next to the line in the gray vertical bar along the left edge of the editor window. 會出現紅色的點。A red dot appears.

    設定中斷點Set a breakpoint

    現在,當我們偵錯程式時,它會一律在該行暫停執行。Now when we debug the program, it always pauses execution at that line. 我們已初步了解程式適用於簡單案例。We already have a rough idea that the program works for simple cases. 因為我們不想要每次都暫停執行,讓我們把中斷點設定為選擇性。Since we don't want to pause execution every time, let's make the breakpoint conditional.

  2. 請在代表中斷點的紅點上按一下滑鼠右鍵,然後選擇 [條件]****。Right-click the red dot that represents the breakpoint, and choose Conditions. 在條件的編輯方塊中,輸入 (y == 0) && (oper == '/')In the edit box for the condition, enter (y == 0) && (oper == '/'). 當您完成時,請選擇 [關閉]**** 按鈕。Choose the Close button when you're done. 條件會自動儲存。The condition is saved automatically.

    設定條件式中斷點Set a conditional breakpoint

    現在我們會在使用者嘗試除以 0 時在中斷點上暫停執行。Now we pause execution at the breakpoint specifically if a division by 0 is attempted.

  3. 若要偵錯程式,請按 F5,或選擇 [本機 Windows 偵錯工具]**** 工具列按鈕 (有綠色箭頭圖示)。To debug the program, press F5, or choose the Local Windows Debugger toolbar button that has the green arrow icon. 在您的主控台應用程式中,若您輸入像是 "5 - 0" 的內容,程式會正常運作並繼續執行。In your console app, if you enter something like "5 - 0", the program behaves normally and keeps running. 但是,若您鍵入 "10 / 0",它便會在中斷點暫停。However, if you type "10 / 0", it pauses at the breakpoint. 您甚至可以在運算子及數字間輸入任意數量的空格,因為 cin 能夠適當地剖析輸入。You can even put any number of spaces between the operator and numbers: cin is smart enough to parse the input appropriately.

    在條件式中斷點暫停Pause at the conditional breakpoint

偵錯工具中有用的視窗Useful windows in the debugger

在您偵錯程式碼時,您可能會注意到其出現了某些新視窗。Whenever you debug your code, you may notice that some new windows appear. 這些視窗可協助您的偵錯體驗。These windows can assist your debugging experience. 讓我們看看 [自動變數]**** 視窗。Take a look at the Autos window. [自動變數]**** 視窗會顯示從至少 3 行以前到目前這一行為止,所使用變數目前的值。The Autos window shows you the current values of variables used at least three lines before and up to the current line. 若要查看來自該函式的所有變數,請切換到 [區域變數]**** 視窗。To see all of the variables from that function, switch to the Locals window. 您實際上可以在偵錯時直接憑空修改這些變數的值,查看其對程式造成的影響。You can actually modify the values of these variables while debugging, to see what effect they would have on the program. 在此案例中,我們不會修改它們的值。In this case, we'll leave them alone.

[區域變數] 視窗The Locals window

您也可以暫留在程式碼本身的變數上,查看它們在目前暫停執行位置上的目前值。You can also just hover over variables in the code itself to see their current values where the execution is currently paused. 請按一下編輯器視窗,確認該視窗仍擁有焦點。Make sure the editor window is in focus by clicking on it first.

暫留以查看目前的變數值Hover to view current variable values

繼續偵錯To continue debugging

  1. 左側黃線會顯示目前的執行點。The yellow line on the left shows the current point of execution. 目前的行會呼叫 Calculate,因此請按 F11 來 [逐步執行]**** 函式。The current line calls Calculate, so press F11 to Step Into the function. 您會看到您進入了 Calculate 函式的主體。You'll find yourself in the body of the Calculate function. 使用 [逐步執行]**** 時請謹慎,若執行太多次,可能會浪費許多時間。Be careful with Step Into; if you do it too much, you may waste a lot of time. 它會進入您在所在行中使用的所有程式碼,包括標準程式庫函式。It goes into any code you use on the line you are on, including standard library functions.

  2. 現在當執行點位於 Calculate 函式的開頭時,請按 F10 來移動到程式執行的下一行。Now that the point of execution is at the start of the Calculate function, press F10 to move to the next line in the program's execution. F10 又稱為 [不進入函式]****。F10 is also known as Step Over. 您可以使用 [不進入函式]**** 來從一行移動到下一行,而無須了解該行每個部分所發生的事件。You can use Step Over to move from line to line, without delving into the details of what is occurring in each part of the line. 一般情況下,建議您使用 [不進入函式]**** 而非 [逐步執行]****,除非您想要更深入地了解從其他位置呼叫的程式碼 (如同您為了觸達 Calculate 主體所進行的操作)。In general you should use Step Over instead of Step Into, unless you want to dive more deeply into code that is being called from elsewhere (as you did to reach the body of Calculate).

  3. 繼續使用 F10不進入每一行函式,直到您回到另一個檔案的 main(),並在 cout 行上停止。Continue using F10 to Step Over each line until you get back to the main() function in the other file, and stop on the cout line.

    看起來程式正如預期般運作:它會接收第一個數字,然後除以第二個數字。It looks like the program is doing what is expected: it takes the first number, and divides it by the second. cout 行上,在 result 變數上暫留或在 [自動變數]**** 視窗中查看 resultOn the cout line, hover over the result variable or take a look at result in the Autos window. 您將會看到其值列出為 "inf",這看起來不正確,因此讓我們修正它吧。You'll see its value is listed as "inf", which doesn't look right, so let's fix it. cout 行只會輸出任何儲存在 result 中的值,因此當您使用 F10 前往下一行時,會顯示主控台視窗:The cout line just outputs whatever value is stored in result, so when you step one more line forward using F10, the console window displays:

    零除的結果The result of divide by zero

    此結果是因為除以零的結果未定義,因此程式針對所要求運算沒有數值答案。This result happens because division by zero is undefined, so the program doesn't have a numerical answer to the requested operation.

修正「除以零」錯誤To fix the "divide by zero" error

讓我們以更好的方式來處理「除以零」,讓使用者能了解問題。Let's handle division by zero more gracefully, so a user can understand the problem.

  1. 請在 CalculatorTutorial.cpp 中進行下列變更。Make the following changes in CalculatorTutorial.cpp. (歸功於稱為 [編輯後繼續]**** 的功能,您可以在編輯的時候讓程式繼續執行):(You can leave the program running as you edit, thanks to a debugger feature called Edit and Continue):

    // CalculatorTutorial.cpp : This file contains the 'main' function. Program execution begins and ends there.
    //
    
    #include <iostream>
    #include "Calculator.h"
    
    using namespace std;
    
    int main()
    {
        double x = 0.0;
        double y = 0.0;
        double result = 0.0;
        char oper = '+';
    
        cout << "Calculator Console Application" << endl << endl;
        cout << "Please enter the operation to perform. Format: a+b | a-b | a*b | a/b" << endl;
    
        Calculator c;
        while (true)
        {
            cin  >> x  >> oper  >> y;
            if (oper == '/' && y == 0)
            {
                cout << "Division by 0 exception" << endl;
                continue;
            }
            else
            {
                result = c.Calculate(x, oper, y);
            }
            cout << "Result is: " << result << endl;
        }
    
        return 0;
    }
    
  2. 現在,請按 F5一次。Now press F5 once. 程式會繼續執行,直到需要暫停要求使用者輸入為止。Program execution continues all the way until it has to pause to ask for user input. 再次輸入 10 / 0Enter 10 / 0 again. 現在會印出更有幫助的訊息。Now, a more helpful message is printed. 程式會向使用者要求更多輸入,且程式會繼續正常執行。The user is asked for more input, and the program continues executing normally.

    變更後的最終結果The final result after changes

    注意

    當您在處於偵錯模式的期間編輯程式碼時,可能會有程式碼過時的風險。When you edit code while in debugging mode, there is a risk of code becoming stale. 這會在偵錯工具仍在執行您的舊版程式碼,且尚未使用您的變更進行更新時發生。This happens when the debugger is still running your old code, and has not yet updated it with your changes. 偵錯工具會在發生此情況時彈出一個對話方塊提醒您。The debugger pops up a dialog to inform you when this happens. 有時候,您可能需要按 F5 來重新整理正在執行的程式碼。Sometimes, you may need to press F5 to refresh the code being executed. 特別是當執行點正位於函式中,而您在該函式的內部進行變更時,您將需要跳出函式,然後再次進入該函式來取得更新後的程式碼。In particular, if you make a change inside a function while the point of execution is inside that function, you'll need to step out of the function, then back into it again to get the updated code. 若因為某些原因仍無法正常運作,且您看到了錯誤訊息,您可以按一下 IDE 頂端功能表下方工具列中的紅色方塊來停止偵錯,然後按 F5 來再次啟動偵錯,或選擇工具列上停止按鈕旁邊的綠色 [執行] 箭頭來進行。If that doesn't work for some reason and you see an error message, you can stop debugging by clicking on the red square in the toolbar under the menus at the top of the IDE, then start debugging again by entering F5 or by choosing the green "play" arrow beside the stop button on the toolbar.

    了解執行和偵錯快速鍵Understanding the Run and Debug shortcuts

    • F5 (或 [偵錯]**** > [開始偵錯]****) 會啟動偵錯工作階段 (若沒有正在使用中的工作階段) 並執行程式,直到到達中斷點或程式需要使用者進行輸入。F5 (or Debug > Start Debugging) starts a debugging session if one isn't already active, and runs the program until a breakpoint is hit or the program needs user input. 若不需要使用者輸入且沒有可到達的中斷點,程式會在完成執行時終止並關閉主控台視窗本身。If no user input is needed and no breakpoint is available to hit, the program terminates and the console window closes itself when the program finishes running. 若您有類似 "Hello World" 的程式要執行,請使用 Ctrl+F5 或設定中斷點,然後按 F5 來將視窗維持在開啟狀態。If you have something like a "Hello World" program to run, use Ctrl+F5 or set a breakpoint before you enter F5 to keep the window open.
    • Ctrl+F5 (或 [偵錯]**** > [啟動但不偵錯]****) 會執行應用程式,而不會進入偵錯模式。Ctrl+F5 (or Debug > Start Without Debugging) runs the application without going into debug mode. 這比偵錯稍快,且主控台視窗會在程式完成執行時維持在開啟狀態。This is slightly faster than debugging, and the console window stays open after the program finishes executing.
    • F10 (又稱為 [不進入函式]****) 可讓您逐一且逐行查看程式碼,並視覺化程式碼執行方式及每個執行步驟中的變數值為何。F10 (known as Step Over) lets you iterate through code, line-by-line, and visualize how the code is run and what variable values are at each step of execution.
    • F11 (又稱為 [逐步執行]****) 的運作方式與 [不進入函式]**** 相似,但它會進入任何在執行行上呼叫的函式。F11 (known as Step Into) works similarly to Step Over, except it steps into any functions called on the line of execution. 例如,當執行的行呼叫一個函式時,按 F11 會將指標移動到函式主體,讓您可以跟隨所執行的函式程式碼,然後回到您開始的那一行。For example, if the line being executed calls a function, pressing F11 moves the pointer into the body of the function, so you can follow the function's code being run before coming back to the line you started at. F10 可不進入函式,直接移動到下一行;函式仍會獲得呼叫,但程式不會暫停並顯示其正在進行的操作。Pressing F10 steps over the function call and just moves to the next line; the function call still happens, but the program doesn't pause to show you what it's doing.

關閉應用程式Close the app

  • 若仍在執行中,請關閉計算機應用程式的主控台視窗。If it's still running, close the console window for the calculator app.

完成的應用程式The finished app

恭喜!Congratulations! 您已完成計算機應用程式的程式碼,並在 Visual Studio 中建置及偵錯。You've completed the code for the calculator app, and built and debugged it in Visual Studio.

後續步驟Next steps

深入了解適用於 C++ 的 Visual StudioLearn more about Visual Studio for C++

通常 C++ 程式設計師的起點都是 "Hello, world!"The usual starting point for a C++ programmer is a "Hello, world!" 應用程式 (在命令列上執行)。application that runs on the command line. 這就是您將在本文中利用 Visual Studio 建立的項目,然後我們會再挑戰更進階的項目:計算機應用程式。That's what you'll create in Visual Studio in this article, and then we'll move on to something more challenging: a calculator app.

必要條件Prerequisites

  • 已在您的電腦上安裝並執行使用 c + + 的桌面開發工作負載 Visual Studio。Have Visual Studio with the Desktop development with C++ workload installed and running on your computer. 若尚未安裝,請參閱 Install C++ support in Visual Studio (在 Visual Studio 中安裝 C++ 支援)。If it's not installed yet, see Install C++ support in Visual Studio.

建立您的應用程式專案Create your app project

Visual Studio 會使用「專案」** 來組織應用程式的程式碼,並使用「解決方案」** 來組織專案。Visual Studio uses projects to organize the code for an app, and solutions to organize your projects. 專案包含用來建置您應用程式的所有選項、組態和規則。A project contains all the options, configurations, and rules used to build your apps. 它也會管理所有專案之檔案與任何外部檔案間的關聯性。It also manages the relationship between all the project's files and any external files. 若要建立您的應用程式,首先,您會建立新的專案及解決方案。To create your app, first, you'll create a new project and solution.

  1. 在 Visual Studio 的功能表列上,選擇 [ 檔案] [新增] [ > New > 專案]。On the menubar in Visual Studio, choose File > New > Project. [新增專案]**** 視窗隨即開啟。The New Project window opens.

  2. 在左邊的側邊欄上,確認已選取 [Visual C++]****。On the left sidebar, make sure Visual C++ is selected. 在中央,選擇 [Windows 主控台應用程式]****。In the center, choose Windows Console Application.

  3. 在底部的 [名稱]**** 編輯方塊中,將新的專案命名為 CalculatorTutorial,然後選擇 [確定]****。In the Name edit box at the bottom, name the new project CalculatorTutorial, then choose OK.

    [新增專案] 對話方塊The New Project dialog

    會建立空白的 C++ Windows 主控台應用程式。An empty C++ Windows console application gets created. 主控台應用程式會使用 Windows 主控台視窗來顯示輸出並接受使用者輸入。Console applications use a Windows console window to display output and accept user input. 在 Visual Studio 中,一個編輯器視窗隨即開啟,並顯示產生的程式碼:In Visual Studio, an editor window opens and shows the generated code:

    // CalculatorTutorial.cpp : This file contains the 'main' function. Program execution begins and ends there.
    //
    
    #include "pch.h"
    #include <iostream>
    
    int main()
    {
        std::cout << "Hello World!\n";
    }
    
    // Run program: Ctrl + F5 or Debug > Start Without Debugging menu
    // Debug program: F5 or Debug > Start Debugging menu
    
    // Tips for Getting Started:
    //   1. Use the Solution Explorer window to add/manage files
    //   2. Use the Team Explorer window to connect to source control
    //   3. Use the Output window to see build output and other messages
    //   4. Use the Error List window to view errors
    //   5. Go to Project > Add New Item to create new code files, or Project > Add Existing Item to add existing code files to the project
    //   6. In the future, to open this project again, go to File > Open > Project and select the .sln file
    

驗證您新的應用程式可以建置及執行Verify that your new app builds and runs

新 Windows 主控台應用程式範本會建立一個簡單的 C++ "Hello World" 應用程式。The template for a new windows console application creates a simple C++ "Hello World" app. 此時,您會看到 Visual Studio 如何直接從 IDE 建置及執行您建立的應用程式。At this point, you can see how Visual Studio builds and runs the apps you create right from the IDE.

  1. 若要建置您的專案,請從 [建置]**** 功能表中選擇 [建置方案]****。To build your project, choose Build Solution from the Build menu. [輸出]**** 視窗會顯示建置過程的結果。The Output window shows the results of the build process.

    建立專案Build the project

  2. 若要執行程式碼,請在功能表列上,選擇 [偵錯]****、[啟動但不偵錯]****。To run the code, on the menu bar, choose Debug, Start without debugging.

    啟動專案Start the project

    主控台視窗會隨即開啟並執行您的應用程式。A console window opens and then runs your app. 當您在 Visual Studio 中啟動主控台應用程式時,它會執行您的程式碼,然後印出「請按任意鍵繼續When you start a console app in Visual Studio, it runs your code, then prints "Press any key to continue . .. ."." 讓您可以有機會查看輸出。to give you a chance to see the output. 恭喜!Congratulations! 您已在 Visual Studio 中建立了您的第一個 "Hello, world!"You've created your first "Hello, world!" 主控台應用程式!console app in Visual Studio!

  3. 請按任意鍵關閉主控台視窗並返回 Visual Studio。Press a key to dismiss the console window and return to Visual Studio.

您現在已具備了在每一項變更之後建置及執行您應用程式的工具,可驗證程式碼仍依照您預期的方式運作。You now have the tools to build and run your app after every change, to verify that the code still works as you expect. 稍後,我們將示範如何在無法正常運作時進行偵錯。Later, we'll show you how to debug it if it doesn't.

編輯程式碼Edit the code

現在,讓我們將此範本中的程式碼轉換成計算機應用程式。Now let's turn the code in this template into a calculator app.

  1. CalculatorTutorial.cpp 檔案中,編輯程式碼,使其與此範例相符:In the CalculatorTutorial.cpp file, edit the code to match this example:

    // CalculatorTutorial.cpp : This file contains the 'main' function. Program execution begins and ends there.
    //
    
    #include "pch.h"
    #include <iostream>
    
    using namespace std;
    
    int main()
    {
        cout << "Calculator Console Application" << endl << endl;
        cout << "Please enter the operation to perform. Format: a+b | a-b | a*b | a/b"
            << endl;
        return 0;
    }
    
    // Run program: Ctrl + F5 or Debug > Start Without Debugging menu
    // Debug program: F5 or Debug > Start Debugging menu
    // Tips for Getting Started:
    //   1. Use the Solution Explorer window to add/manage files
    //   2. Use the Team Explorer window to connect to source control
    //   3. Use the Output window to see build output and other messages
    //   4. Use the Error List window to view errors
    //   5. Go to Project > Add New Item to create new code files, or Project > Add Existing Item to add existing code files to the project
    //   6. In the future, to open this project again, go to File > Open > Project and select the .sln file
    

    了解程式碼:Understanding the code:

    • #include 陳述式可讓您參考位於其他檔案中的程式碼。The #include statements allow you to reference code located in other files. 有時候,您可能會看到以角括弧()括住的檔案名 <> ; 其他時間則是以引號("")括住。Sometimes, you may see a filename surrounded by angle brackets (<>); other times, it's surrounded by quotes (" "). 一般情況下,角括弧會在參考 C++ 標準程式庫時使用,引號則用於其他檔案。In general, angle brackets are used when referencing the C++ Standard Library, while quotes are used for other files.
    • #include "pch.h" (或在 Visual Studio 2017 與較舊版本中則為 #include "stdafx.h") 行參考稱為先行編譯標頭檔的項目。The #include "pch.h" (or in Visual Studio 2017 and earlier, #include "stdafx.h") line references something known as a precompiled header. 這通常會由專業程式設計師使用,用來改善編譯時間,但這不在本教學課程的範圍內。These are often used by professional programmers to improve compilation times, but they are beyond the scope of this tutorial.
    • using namespace std; 這一行則會告知編譯器,預期在此檔案中使用來自 C++ 標準程式庫的功能。The using namespace std; line tells the compiler to expect stuff from the C++ Standard Library to be used in this file. 若沒有這一行,每個來自程式庫的關鍵字都必須在開頭加上 std:: 以表示其範圍。Without this line, each keyword from the library would have to be preceded with a std::, to denote its scope. 例如,若沒有該行,每個對 cout 的參考都必須寫成 std::coutFor instance, without that line, each reference to cout would have to be written as std::cout. using 已加入語句,讓程式碼看起來更清楚。The using statement is added to make the code look more clean.
    • cout 關鍵字則用於印出至 C++ 中的標準輸出。The cout keyword is used to print to standard output in C++. << 運算子會指示編譯器將其右邊的任何內容傳送至標準輸出。The << operator tells the compiler to send whatever is to the right of it to the standard output.
    • endl 關鍵字則像是 Enter 鍵,它會結束這一行並將游標移到下一行。The endl keyword is like the Enter key; it ends the line and moves the cursor to the next line. \n 放在字串內部 (即包含在 "" 中) 以進行相同操作是較佳的做法,因為 endl 會排清緩衝區而可能影響程式的效能,但由於這個應用程式很小,所以我們在此處使用 endl 來改善可讀性。It is a better practice to put a \n inside the string (contained by "") to do the same thing, as endl always flushes the buffer and can hurt the performance of the program, but since this is a very small app, endl is used instead for better readability.
    • 所有 C++ 陳述式都必須以分號結尾,且所有的 C++ 應用程式都必須包含一個 main() 函式。All C++ statements must end with semicolons and all C++ applications must contain a main() function. 此函式是程式在開始時執行的部分。This function is what the program runs at the start. 所有程式碼都必須要能夠從 main() 存取,才能使用。All code must be accessible from main() in order to be used.
  2. 若要儲存檔案,請按下 Ctrl+S,或選擇靠近 IDE 頂端的儲存圖示,即功能表列下方工具列中的磁碟片圖示。To save the file, enter Ctrl+S, or choose the Save icon near the top of the IDE, the floppy disk icon in the toolbar under the menu bar.

  3. 若要執行應用程式,請按下 Ctrl+F5,或前往 [偵錯]**** 功能表,然後選擇 [啟動但不偵錯]****。To run the application, press Ctrl+F5 or go to the Debug menu and choose Start Without Debugging. 若您看到 [此專案已過期]**** 快顯訊息,您可以選取 [不要再顯示此對話方塊]****,然後選擇 [是]**** 來建置您的應用程式。If you get a pop-up that says This project is out of date, you may select Do not show this dialog again, and then choose Yes to build your application. 您應該會看到一個主控台視窗出現,它顯示程式碼中指定的文字。You should see a console window appear that displays the text specified in the code.

    建立並啟動您的應用程式Build and start your application

  4. 當您完成時,請關閉主控台視窗。Close the console window when you're done.

新增程式碼來執行數學運算Add code to do some math

是時候新增一些數學邏輯了。It's time to add some math logic.

新增 Calculator 類別To add a Calculator class

  1. 前往 [專案]**** 功能表,然後選擇 [新增類別]****。Go to the Project menu and choose Add Class. 在 [類別名稱]**** 編輯方塊中,輸入 CalculatorIn the Class Name edit box, enter Calculator. 選擇 [確定]。Choose OK. 會將兩個新檔案新增到您的專案。Two new files get added to your project. 若要一次儲存您所有變更的檔案,請按 Ctrl+Shift+STo save all your changed files at once, press Ctrl+Shift+S. 這是 [檔案] [ File > 全部儲存] 的鍵盤快速鍵。It's a keyboard shortcut for File > Save All. [全部儲存]**** 也有一個工具列按鈕,即兩個磁碟片的圖示,您可在 [儲存]**** 按鈕的旁邊找到。There's also a toolbar button for Save All, an icon of two floppy disks, found beside the Save button. 一般情況下,頻繁地進行 [全部儲存]**** 是良好的做法,因為這樣可避免您在儲存時遺漏任何檔案。In general, it's good practice to do Save All frequently, so you don't miss any files when you save.

    建立計算機類別Create the Calculator class

    類別就像是物件的藍圖,可進行某些操作。A class is like a blueprint for an object that does something. 在此案例中,我們會定義一個計算機及其運作的方式。In this case, we define a calculator and how it should work. 您在上方使用的 [新增類別精靈]**** 會建立 .h 及 .cpp 檔案,且其名稱和類別皆相同。The Add Class wizard you used above created .h and .cpp files that have the same name as the class. 您可以在 [方案總管] 視窗中看到專案檔案的完整清單,在 IDE 的側邊看到。You can see a full list of your project files in the Solution Explorer window, visible on the side of the IDE. 如果看不到視窗,您可以從功能表列開啟它:選擇 [ View > 方案總管]。If the window isn't visible, you can open it from the menu bar: choose View > Solution Explorer.

    方案總管Solution Explorer

    您現在應該會在編輯器中開啟三個索引標籤: calculatortutorial.cpp .cpp計算機 .h計算機 .cppYou should now have three tabs open in the editor: CalculatorTutorial.cpp, Calculator.h, and Calculator.cpp. 如果您不小心關閉其中一個,您可以在 [方案總管] 視窗中按兩下它來重新開啟。If you accidentally close one of them, you can reopen it by double-clicking it in the Solution Explorer window.

  2. Calculator.h 中,移除所產生的 Calculator();~Calculator(); 這兩行,因為您在此處不需要它們。In Calculator.h, remove the Calculator(); and ~Calculator(); lines that were generated, since you won't need them here. 接下來,請新增下列這行程式碼,使其看起來與下列內容相似:Next, add the following line of code so the file now looks like this:

    #pragma once
    class Calculator
    {
    public:
        double Calculate(double x, char oper, double y);
    };
    

    了解程式碼Understanding the code

    • 您新增的這一行會宣告一個稱為 Calculate 的新函式,我們會使用此函式來進行數學運算,包含加、減、乘及除。The line you added declares a new function called Calculate, which we'll use to run math operations for addition, subtraction, multiplication, and division.
    • C++ 程式碼會整理成「標頭」(.h) 檔案及「來源」(.cpp) 檔案。C++ code is organized into header (.h) files and source (.cpp) files. 各種編譯器還支援數種其他副檔名,但這些是您需了解的主要項目。Several other file extensions are supported by various compilers, but these are the main ones to know about. 函式和變數通常會經過「宣告」,即在標頭檔中提供名稱和型別,然後在來源檔案中「實作」(或提供定義)。Functions and variables are normally declared, that is, given a name and a type, in header files, and implemented, or given a definition, in source files. 若要存取另一個檔案中定義的程式碼,您可以使用 #include "filename.h",其中 'filename.h' 是宣告您欲使用變數或函式的檔案名稱。To access code defined in another file, you can use #include "filename.h", where 'filename.h' is the name of the file that declares the variables or functions you want to use.
    • 您刪除之兩行會宣告類別的「建構函式」** 及「解構函式」**。The two lines you deleted declared a constructor and destructor for the class. 針對如此範例的簡單類別,編譯器會為您建立它們,且其使用用途也不在本教學課程的範圍內。For a simple class like this one, the compiler creates them for you, and their uses are beyond the scope of this tutorial.
    • 將您的程式碼根據其用途整理成不同檔案是一種良好做法,因為這可讓您在稍後需要的時候輕易地尋找它們。It's good practice to organize your code into different files based on what it does, so it's easy to find the code you need later. 在我們的案例中,我們將 Calculator 類別與包含 main() 函式的檔案分開來定義,但我們計劃在 main() 中參考 Calculator 類別。In our case, we define the Calculator class separately from the file containing the main() function, but we plan to reference the Calculator class in main().
  3. 您會在 Calculate 的下方看到綠色的彎曲箭號。You'll see a green squiggle appear under Calculate. 這是因為我們尚未在 .cpp 檔案中定義 Calculate 函式。It's because we haven't defined the Calculate function in the .cpp file. 暫留在文字上,按一下彈出的燈泡,然後選擇 [在 Calculator.cpp 中建立 'Calculate' 的定義]****。Hover over the word, click the lightbulb that pops up, and choose Create definition of 'Calculate' in Calculator.cpp. 快顯視窗隨即出現,可讓您預覽在其他檔案中進行的程式碼變更。A pop-up appears that gives you a peek of the code change that was made in the other file. 程式碼已新增至 Calculator.cppThe code was added to Calculator.cpp.

    建立計算的定義Create definition of Calculate

    目前,它只會傳回 0.0。Currently, it just returns 0.0. 讓我們改變這點。Let's change that. Esc 來關閉快顯視窗。Press Esc to close the pop-up.

  4. 在編輯器視窗中切換至 Calculator.cpp 檔案。Switch to the Calculator.cpp file in the editor window. 移除 Calculator()~Calculator() 這兩個區段 (如同您在 .h 檔案中所進行的操作),並將下列程式碼新增至 Calculate()Remove the Calculator() and ~Calculator() sections (as you did in the .h file) and add the following code to Calculate():

    #include "pch.h"
    #include "Calculator.h"
    
    double Calculator::Calculate(double x, char oper, double y)
    {
        switch(oper)
        {
            case '+':
                return x + y;
            case '-':
                return x - y;
            case '*':
                return x * y;
            case '/':
                return x / y;
            default:
                return 0.0;
        }
    }
    

    了解程式碼Understanding the code

    • Calculate 函式會取用一個數字、一個運算子及第二個數字,然後在數字上執行所要求的運算。The function Calculate consumes a number, an operator, and a second number, then performs the requested operation on the numbers.
    • Switch 陳述式會檢查提供的運算子為何,並只執行對應至該運算的案例。The switch statement checks which operator was provided, and only executes the case corresponding to that operation. default: 案例是一種後援案例,若使用者鍵入不接受的運算子,即會使用此案例以避免中斷程式。The default: case is a fallback in case the user types an operator that isn't accepted, so the program doesn't break. 一般情況下,使用更簡潔的方式處理無效使用者輸入會是最佳做法,但這不在本教學課程的範圍內。In general, it's best to handle invalid user input in a more elegant way, but this is beyond the scope of this tutorial.
    • double 關鍵字代表支援小數的數位類型。The double keyword denotes a type of number that supports decimals. 如此一來,計算機便能夠同時處理小數點及整數的數學運算。This way, the calculator can handle both decimal math and integer math. 函式 Calculate 必須一律傳回這類數位,因為程式碼的 double 開頭是(這表示函式的傳回型別),這就是為什麼我們會傳回0.0,即使是在預設情況下也是如此。The Calculate function is required to always return such a number due to the double at the very start of the code (this denotes the function's return type), which is why we return 0.0 even in the default case.
    • .h 檔案會宣告函式的「原型」**,預先告知編譯器其需要的參數,以及該預期的傳回型別為何。The .h file declares the function prototype, which tells the compiler upfront what parameters it requires, and what return type to expect from it. .cpp 檔案則包含函式所有的實作詳細資料。The .cpp file has all the implementation details of the function.

如果您此時再次建置並執行程式碼,其仍會在詢問要執行哪項作業後結束。If you build and run the code again at this point, it will still exit after asking which operation to perform. 接下來,您會修改 main 函式來進行一些運算。Next, you'll modify the main function to do some calculations.

呼叫 Calculator 類別成員函式To call the Calculator class member functions

  1. 現在讓我們來更新 CalculatorTutorial.cpp 中的 main 函式:Now let's update the main function in CalculatorTutorial.cpp:

    // CalculatorTutorial.cpp : This file contains the 'main' function. Program execution begins and ends there.
    //
    
    #include "pch.h"
    #include <iostream>
    #include "Calculator.h"
    
    using namespace std;
    
    int main()
    {
        double x = 0.0;
        double y = 0.0;
        double result = 0.0;
        char oper = '+';
    
        cout << "Calculator Console Application" << endl << endl;
        cout << "Please enter the operation to perform. Format: a+b | a-b | a*b | a/b"
             << endl;
    
        Calculator c;
        while (true)
        {
            cin >> x >> oper >> y;
            result = c.Calculate(x, oper, y);
            cout << "Result is: " << result << endl;
        }
    
        return 0;
    }
    

    了解程式碼Understanding the code

    • 由於 C++ 程式一律會從 main() 函式開始,而我們需要從該處呼叫我們的其他程式碼,因此需要 #include 陳述式。Since C++ programs always start at the main() function, we need to call our other code from there, so a #include statement is needed.
    • 我們宣告了某些初始變數 xyoperresult,分別用來儲存第一個數字、第二個數字、運算子及最終結果。Some initial variables x, y, oper, and result are declared to store the first number, second number, operator, and final result, respectively. 提供它們某些初始值以避免未定義的行為是一種良好做法,而我們也在此處進行了這項操作。It is always good practice to give them some initial values to avoid undefined behavior, which is what is done here.
    • Calculator c; 這一行會宣告一個名為 'c' 的物件,作為 Calculator 類別的執行個體。The Calculator c; line declares an object named 'c' as an instance of the Calculator class. 類別本身只是計算機運作的藍圖;物件則是進行數學運算的特定計算機。The class itself is just a blueprint for how calculators work; the object is the specific calculator that does the math.
    • while (true) 陳述式是一種迴圈。The while (true) statement is a loop. 只要 () 內的條件為 True,迴圈內的程式碼就會繼續重複執行。The code inside the loop continues to execute over and over again as long as the condition inside the () holds true. 因為此條件只會列為 true ,所以一律為 true,因此迴圈會永遠執行。Since the condition is simply listed as true, it's always true, so the loop runs forever. 若要關閉程式,使用者必須手動關閉主控台視窗。To close the program, the user must manually close the console window. 否則,程式一律都會等待新的輸入。Otherwise, the program always waits for new input.
    • cin 關鍵字則用於接受使用者的輸入。The cin keyword is used to accept input from the user. 假設使用者輸入符合必要規格,輸入串流便能處理在主控台視窗中輸入的文字行,並依序將它放在每個列出的變數內。This input stream is smart enough to process a line of text entered in the console window and place it inside each of the variables listed, in order, assuming the user input matches the required specification. 您可以修改此行來接受不同類型的輸入 (例如兩個以上的數字),雖然 Calculate() 函式也需要更新才能進行處理。You can modify this line to accept different types of input, for instance, more than two numbers, though the Calculate() function would also need to be updated to handle this.
    • c.Calculate(x, oper, y); 運算式會呼叫先前定義的 Calculate 函式,並提供輸入的輸入值。The c.Calculate(x, oper, y); expression calls the Calculate function defined earlier, and supplies the entered input values. 函式接著會傳回儲存在 result 中的數字。The function then returns a number that gets stored in result.
    • 最後,result 會印出到主控台,讓使用者看見運算的結果。Finally, result is printed to the console, so the user sees the result of the calculation.

再次建置並測試程式碼Build and test the code again

現在,是時候再次測試程式以確認所有功能皆正常運作了。Now it's time to test the program again to make sure everything works properly.

  1. 請按 Ctrl+F5 來重新建置並啟動應用程式。Press Ctrl+F5 to rebuild and start the app.

  2. 輸入 5 + 5 ,然後按enter鍵。Enter 5 + 5, and press Enter. 驗證結果為 10。Verify that the result is 10.

    5 + 5 的結果The result of 5 + 5

偵錯應用程式Debug the app

因為使用者可以在主控台視窗中鍵入任何內容,讓我們確認計算機能依照預期的方式處理某些輸入。Since the user is free to type anything into the console window, let's make sure the calculator handles some input as expected. 相較於執行程式,我們可以改為針對它進行偵錯,讓我們可以詳細地逐步檢查其進行的作業。Instead of running the program, let's debug it instead, so we can inspect what it's doing in detail, step-by-step.

在偵錯工具中執行應用程式To run the app in the debugger

  1. result = c.Calculate(x, oper, y); 這一行設定中斷點,即在向使用者要求輸入之後。Set a breakpoint on the result = c.Calculate(x, oper, y); line, just after the user was asked for input. 若要設定中斷點,請按一下編輯器視窗左邊緣灰色垂直列中的行。To set the breakpoint, click next to the line in the gray vertical bar along the left edge of the editor window. 會出現紅色的點。A red dot appears.

    設定中斷點Set a breakpoint

    現在,當我們偵錯程式時,它會一律在該行暫停執行。Now when we debug the program, it always pauses execution at that line. 我們已初步了解程式適用於簡單案例。We already have a rough idea that the program works for simple cases. 因為我們不想要每次都暫停執行,讓我們把中斷點設定為選擇性。Since we don't want to pause execution every time, let's make the breakpoint conditional.

  2. 請在代表中斷點的紅點上按一下滑鼠右鍵,然後選擇 [條件]****。Right-click the red dot that represents the breakpoint, and choose Conditions. 在條件的編輯方塊中,輸入 (y == 0) && (oper == '/')In the edit box for the condition, enter (y == 0) && (oper == '/'). 當您完成時,請選擇 [關閉]**** 按鈕。Choose the Close button when you're done. 條件會自動儲存。The condition is saved automatically.

    設定條件式中斷點Set a conditional breakpoint

    現在我們會在使用者嘗試除以 0 時在中斷點上暫停執行。Now we pause execution at the breakpoint specifically if a division by 0 is attempted.

  3. 若要偵錯程式,請按 F5,或選擇 [本機 Windows 偵錯工具]**** 工具列按鈕 (有綠色箭頭圖示)。To debug the program, press F5, or choose the Local Windows Debugger toolbar button that has the green arrow icon. 在您的主控台應用程式中,若您輸入像是 "5 - 0" 的內容,程式會正常運作並繼續執行。In your console app, if you enter something like "5 - 0", the program behaves normally and keeps running. 但是,若您鍵入 "10 / 0",它便會在中斷點暫停。However, if you type "10 / 0", it pauses at the breakpoint. 您甚至可以在運算子及數字間輸入任意數量的空格,因為 cin 能夠適當地剖析輸入。You can even put any number of spaces between the operator and numbers; cin is smart enough to parse the input appropriately.

    在條件式中斷點暫停Pause at the conditional breakpoint

偵錯工具中有用的視窗Useful windows in the debugger

在您偵錯程式碼時,您可能會注意到其出現了某些新視窗。Whenever you debug your code, you may notice that some new windows appear. 這些視窗可協助您的偵錯體驗。These windows can assist your debugging experience. 讓我們看看 [自動變數]**** 視窗。Take a look at the Autos window. [自動變數]**** 視窗會顯示從至少 3 行以前到目前這一行為止,所使用變數目前的值。The Autos window shows you the current values of variables used at least three lines before and up to the current line.

[自動變數] 視窗The Autos window

若要查看來自該函式的所有變數,請切換到 [區域變數]**** 視窗。To see all of the variables from that function, switch to the Locals window. 您實際上可以在偵錯時直接憑空修改這些變數的值,查看其對程式造成的影響。You can actually modify the values of these variables while debugging, to see what effect they would have on the program. 在此案例中,我們不會修改它們的值。In this case, we'll leave them alone.

[區域變數] 視窗The Locals window

您也可以暫留在程式碼本身的變數上,查看它們在目前暫停執行位置上的目前值。You can also just hover over variables in the code itself to see their current values where the execution is currently paused. 請按一下編輯器視窗,確認該視窗仍擁有焦點。Make sure the editor window is in focus by clicking on it first.

暫留以查看目前的變數值Hover to view current variable values

繼續偵錯To continue debugging

  1. 左側黃線會顯示目前的執行點。The yellow line on the left shows the current point of execution. 目前的行會呼叫 Calculate,因此請按 F11 來 [逐步執行]**** 函式。The current line calls Calculate, so press F11 to Step Into the function. 您會看到您進入了 Calculate 函式的主體。You'll find yourself in the body of the Calculate function. 使用 [逐步執行]**** 時請謹慎,若執行太多次,可能會浪費許多時間。Be careful with Step Into; if you do it too much, you may waste a lot of time. 它會進入您在所在行中使用的所有程式碼,包括標準程式庫函式。It goes into any code you use on the line you are on, including standard library functions.

  2. 現在當執行點位於 Calculate 函式的開頭時,請按 F10 來移動到程式執行的下一行。Now that the point of execution is at the start of the Calculate function, press F10 to move to the next line in the program's execution. F10 又稱為 [不進入函式]****。F10 is also known as Step Over. 您可以使用 [不進入函式]**** 來從一行移動到下一行,而無須了解該行每個部分所發生的事件。You can use Step Over to move from line to line, without delving into the details of what is occurring in each part of the line. 一般情況下,建議您使用 [不進入函式]**** 而非 [逐步執行]****,除非您想要更深入地了解從其他位置呼叫的程式碼 (如同您為了觸達 Calculate 主體所進行的操作)。In general you should use Step Over instead of Step Into, unless you want to dive more deeply into code that is being called from elsewhere (as you did to reach the body of Calculate).

  3. 繼續使用 F10不進入每一行函式,直到您回到另一個檔案的 main(),並在 cout 行上停止。Continue using F10 to Step Over each line until you get back to the main() function in the other file, and stop on the cout line.

    跳出計算和檢查結果Step out of Calculate and check result

    看起來程式正如預期般運作:它會接收第一個數字,然後除以第二個數字。It looks like the program is doing what is expected: it takes the first number, and divides it by the second. cout 行上,在 result 變數上暫留或在 [自動變數]**** 視窗中查看 resultOn the cout line, hover over the result variable or take a look at result in the Autos window. 您將會看到其值列出為 "inf",這看起來不正確,因此讓我們修正它吧。You'll see its value is listed as "inf", which doesn't look right, so let's fix it. cout 行只會輸出任何儲存在 result 中的值,因此當您使用 F10 前往下一行時,會顯示主控台視窗:The cout line just outputs whatever value is stored in result, so when you step one more line forward using F10, the console window displays:

    零除的結果The result of divide by zero

    此結果是因為除以零的結果未定義,因此程式針對所要求運算沒有數值答案。This result happens because division by zero is undefined, so the program doesn't have a numerical answer to the requested operation.

修正「除以零」錯誤To fix the "divide by zero" error

讓我們以更好的方式來處理「除以零」,讓使用者能了解問題。Let's handle division by zero more gracefully, so a user can understand the problem.

  1. 請在 CalculatorTutorial.cpp 中進行下列變更。Make the following changes in CalculatorTutorial.cpp. (歸功於稱為 [編輯後繼續]**** 的功能,您可以在編輯的時候讓程式繼續執行):(You can leave the program running as you edit, thanks to a debugger feature called Edit and Continue):

    // CalculatorTutorial.cpp : This file contains the 'main' function. Program execution begins and ends there.
    //
    
    #include "pch.h"
    #include <iostream>
    #include "Calculator.h"
    
    using namespace std;
    
    int main()
    {
        double x = 0.0;
        double y = 0.0;
        double result = 0.0;
        char oper = '+';
    
        cout << "Calculator Console Application" << endl << endl;
        cout << "Please enter the operation to perform. Format: a+b | a-b | a*b | a/b" << endl;
    
        Calculator c;
        while (true)
        {
            cin  >> x  >> oper  >> y;
            if (oper == '/' && y == 0)
            {
                cout << "Division by 0 exception" << endl;
                continue;
            }
            else
            {
                result = c.Calculate(x, oper, y);
            }
            cout << "Result is: " << result << endl;
        }
    
        return 0;
    }
    
  2. 現在,請按 F5一次。Now press F5 once. 程式會繼續執行,直到需要暫停要求使用者輸入為止。Program execution continues all the way until it has to pause to ask for user input. 再次輸入 10 / 0Enter 10 / 0 again. 現在會印出更有幫助的訊息。Now, a more helpful message is printed. 程式會向使用者要求更多輸入,且程式會繼續正常執行。The user is asked for more input, and the program continues executing normally.

    變更後的最終結果The final result after changes

    注意

    當您在處於偵錯模式的期間編輯程式碼時,可能會有程式碼過時的風險。When you edit code while in debugging mode, there is a risk of code becoming stale. 這會在偵錯工具仍在執行您的舊版程式碼,且尚未使用您的變更進行更新時發生。This happens when the debugger is still running your old code, and has not yet updated it with your changes. 偵錯工具會在發生此情況時彈出一個對話方塊提醒您。The debugger pops up a dialog to inform you when this happens. 有時候,您可能需要按 F5 來重新整理正在執行的程式碼。Sometimes, you may need to press F5 to refresh the code being executed. 特別是當執行點正位於函式中,而您在該函式的內部進行變更時,您將需要跳出函式,然後再次進入該函式來取得更新後的程式碼。In particular, if you make a change inside a function while the point of execution is inside that function, you'll need to step out of the function, then back into it again to get the updated code. 若因為某些原因仍無法正常運作,且您看到了錯誤訊息,您可以按一下 IDE 頂端功能表下方工具列中的紅色方塊來停止偵錯,然後按 F5 來再次啟動偵錯,或選擇工具列上停止按鈕旁邊的綠色 [執行] 箭頭來進行。If that doesn't work for some reason and you see an error message, you can stop debugging by clicking on the red square in the toolbar under the menus at the top of the IDE, then start debugging again by entering F5 or by choosing the green "play" arrow beside the stop button on the toolbar.

    了解執行和偵錯快速鍵Understanding the Run and Debug shortcuts

    • F5 (或 [偵錯]**** > [開始偵錯]****) 會啟動偵錯工作階段 (若沒有正在使用中的工作階段) 並執行程式,直到到達中斷點或程式需要使用者進行輸入。F5 (or Debug > Start Debugging) starts a debugging session if one isn't already active, and runs the program until a breakpoint is hit or the program needs user input. 若不需要使用者輸入且沒有可到達的中斷點,程式會在完成執行時終止並關閉主控台視窗本身。If no user input is needed and no breakpoint is available to hit, the program terminates and the console window closes itself when the program finishes running. 若您有類似 "Hello World" 的程式要執行,請使用 Ctrl+F5 或設定中斷點,然後按 F5 來將視窗維持在開啟狀態。If you have something like a "Hello World" program to run, use Ctrl+F5 or set a breakpoint before you enter F5 to keep the window open.
    • Ctrl+F5 (或 [偵錯]**** > [啟動但不偵錯]****) 會執行應用程式,而不會進入偵錯模式。Ctrl+F5 (or Debug > Start Without Debugging) runs the application without going into debug mode. 這比偵錯稍快,且主控台視窗會在程式完成執行時維持在開啟狀態。This is slightly faster than debugging, and the console window stays open after the program finishes executing.
    • F10 (又稱為 [不進入函式]****) 可讓您逐一且逐行查看程式碼,並視覺化程式碼執行方式及每個執行步驟中的變數值為何。F10 (known as Step Over) lets you iterate through code, line-by-line, and visualize how the code is run and what variable values are at each step of execution.
    • F11 (又稱為 [逐步執行]****) 的運作方式與 [不進入函式]**** 相似,但它會進入任何在執行行上呼叫的函式。F11 (known as Step Into) works similarly to Step Over, except it steps into any functions called on the line of execution. 例如,當執行的行呼叫一個函式時,按 F11 會將指標移動到函式主體,讓您可以跟隨所執行的函式程式碼,然後回到您開始的那一行。For example, if the line being executed calls a function, pressing F11 moves the pointer into the body of the function, so you can follow the function's code being run before coming back to the line you started at. F10 可不進入函式,直接移動到下一行;函式仍會獲得呼叫,但程式不會暫停並顯示其正在進行的操作。Pressing F10 steps over the function call and just moves to the next line; the function call still happens, but the program doesn't pause to show you what it's doing.

關閉應用程式Close the app

  • 若仍在執行中,請關閉計算機應用程式的主控台視窗。If it's still running, close the console window for the calculator app.

完成的應用程式The finished app

恭喜!Congratulations! 您已完成計算機應用程式的程式碼,並在 Visual Studio 中建置及偵錯。You've completed the code for the calculator app, and built and debugged it in Visual Studio.

後續步驟Next steps

深入了解適用於 C++ 的 Visual StudioLearn more about Visual Studio for C++