本文內容
創建 C++ 控制台應用項目Create a C++ console app project
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
-
- 在 Visual Studio 中安裝“使用 C++ 的桌面開發”工作負載並在計算機上運行。Have Visual Studio with the Desktop development with C++ workload installed and running on your computer. 如果尚未安裝,請參閱在 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.
-
-
如果剛剛啟動 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 中的菜單欄上,選擇“文件” > “新建” > “項目”。Otherwise, on the menubar in Visual Studio, choose File > New > Project. “創建新項目”窗口隨即打開。The Create a new project window opens.
-
在項目模板列表中,選擇“控制台應用”,然后選擇“下一步”。In the list of project templates, choose Console App, then choose Next.


重要
請確保選擇 Console App 模板的 C++ 版本。Make sure you choose the C++ version of the Console App template. 它具有 C++、Windows 和 Console 標記,該圖標在角落處有“++”。It has the C++, Windows, and Console tags, and the icon has "++" in the corner.
-
在“配置新項目”對話框中,選擇“項目名稱”編輯框,將新項目命名為 CalculatorTutorial,然后選擇“創建”。In the Configure your new project dialog box, select the Project name edit box, name your new project CalculatorTutorial, then choose Create.


將創建一個空的 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:
C++// 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.
-
-
若要生成項目,請從“生成”菜單選擇“生成解決方案”。To build your project, choose Build Solution from the Build menu. “輸出”窗口將顯示生成過程的結果。The Output window shows the results of the build process.


-
若要運行代碼,請在菜單欄上選擇“調試”、“開始執行(不調試)”。To run the code, on the menu bar, choose Debug, Start without debugging.


隨即將打開控制台窗口,然后運行你的應用。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!
-
按任意鍵關閉該控制台窗口並返回到 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.
-
-
在“CalculatorTutorial.cpp”文件中,編輯代碼以匹配此示例:In the CalculatorTutorial.cpp file, edit the code to match this example:
C++// 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#includestatements 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++ 標准庫中的內容。Theusing 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 astd::, to denote its scope. 例如,如果沒有該行,則對cout的每個引用都必須寫為std::cout。For instance, without that line, each reference tocoutwould have to be written asstd::cout.using語句的使用是為了使代碼看起來更干凈。Theusingstatement is added to make the code look more clean.cout關鍵字用於在 C++ 中打印到標准輸出。Thecoutkeyword 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\ninside the string (contained by "") to do the same thing, asendlalways flushes the buffer and can hurt the performance of the program, but since this is a very small app,endlis used instead for better readability. - 所有 C++ 語句都必須以分號結尾,所有 C++ 應用程序都必須包含
main()函數。All C++ statements must end with semicolons and all C++ applications must contain amain()function. 該函數是程序開始運行時運行的函數。This function is what the program runs at the start. 若要使用所有代碼,必須可從main()訪問所有代碼。All code must be accessible frommain()in order to be used.
-
要保存文件,請輸入“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.
-
要運行該應用程序,請按“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.
-
完成后,請關閉控制台窗口。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
-
-
轉到“項目”菜單,並選擇“添加類”。Go to the Project menu and choose Add Class. 在“類名”編輯框中,輸入“Calculator”。In the Class Name edit box, enter Calculator. 選擇 “確定”。Choose OK. 這會向項目中添加兩個新文件。Two new files get added to your project. 若要同時保存所有已更改的文件,請按“Ctrl+Shift+S”。To save all your changed files at once, press Ctrl+Shift+S. 這是“文件” > “全部保存”的鍵盤快捷方式。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.


類就像執行某事的對象的藍圖。A class is like a blueprint for an object that does something. 在本示例中,我們定義了 Calculator 以及它的工作原理。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. 如果該窗口不可見,則可從菜單欄中打開它:選擇“查看” > “解決方案資源管理器”。If the window isn't visible, you can open it from the menu bar: choose View > Solution Explorer.


現在編輯器中應打開了三個選項卡:CalculatorTutorial.cpp、Calculator.h 和 Calculator.cpp。You 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.
-
在“Calculator.h”中,刪除生成的
Calculator();和~Calculator();行,因為在此處不需要它們。In Calculator.h, remove theCalculator();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:C++#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 calledCalculate, 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 theCalculatorclass separately from the file containing themain()function, but we plan to reference theCalculatorclass inmain().
- 所添加的行聲明了一個名為
-
你會看到
Calculate下顯示綠色波浪線。You'll see a green squiggle appear underCalculate. 因為我們還沒有在 .cpp 文件中定義Calculate函數。It's because we haven't defined theCalculatefunction 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.

隨即將出現一個彈出窗口,可在其中查看在另一個文件中進行的代碼更改。A pop-up appears that gives you a peek of the code change that was made in the other file. 該代碼已添加到“Calculator.cpp”。The code was added to Calculator.cpp.


目前,它只返回 0.0。Currently, it just returns 0.0. 讓我們來更改它。Let's change that. 按 Esc 關閉彈出窗口。Press Esc to close the pop-up.
-
切換到編輯器窗口中的“Calculator.cpp”文件。Switch to the Calculator.cpp file in the editor window. 刪除
Calculator()和~Calculator()部分(就像在 .h 文件中一樣)並將以下代碼添加到Calculate():Remove theCalculator()and~Calculator()sections (as you did in the .h file) and add the following code toCalculate():C++#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 functionCalculateconsumes 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: case”是一個回滾,以防用戶鍵入一個不被接受的運算符,因此程序不會中斷。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關鍵字表示支持小數的數字類型。Thedoublekeyword denotes a type of number that supports decimals. 因此,Calculator 可以處理十進制數學和整數數學。This way, the calculator can handle both decimal math and integer math. 要始終返回這樣的數字,需要Calculate函數,因為代碼的最開始是double(這表示函數的返回類型),這就是為什么我們在默認情況下返回 0.0。TheCalculatefunction is required to always return such a number due to thedoubleat 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
-
-
現在讓我們更新“CalculatorTutorial.cpp”中的
main函數:Now let's update themainfunction in CalculatorTutorial.cpp:C++// 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 themain()function, we need to call our other code from there, so a#includestatement is needed. - 聲明了一些初始變量
x、y、oper和result,分別用於存儲第一個數字、第二個數字、運算符和最終結果。Some initial variablesx,y,oper, andresultare 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類的實例。TheCalculator c;line declares an object named 'c' as an instance of theCalculatorclass. 類本身只是計算器工作方式的藍圖;對象是進行數學運算的特定計算器。The class itself is just a blueprint for how calculators work; the object is the specific calculator that does the math.while (true)語句是一個循環。Thewhile (true)statement is a loop. 只要()內的條件成立,循環內的代碼就會一遍又一遍地執行。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 astrue, 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關鍵字用於接受來自用戶的輸入。Thecinkeyword 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 theCalculate()function would also need to be updated to handle this.c.Calculate(x, oper, y);表達式調用前面定義的Calculate函數,並提供輸入的輸入值。Thec.Calculate(x, oper, y);expression calls theCalculatefunction defined earlier, and supplies the entered input values. 然后該函數返回一個存儲在result中的數字。The function then returns a number that gets stored inresult.- 最后,將
result輸出到控制台,以便用戶查看計算結果。Finally,resultis printed to the console, so the user sees the result of the calculation.
- 由於 C++ 程序總是從
-
再次生成和測試代碼Build and test the code again
現在是時候再次測試程序以確保一切正常。Now it's time to test the program again to make sure everything works properly.
-
-
按“Ctrl+F5”重建並啟動應用。Press Ctrl+F5 to rebuild and start the app.
-
輸入
5 + 5,然后按 Enter。Enter5 + 5, and press Enter. 驗證結果是否為 10。Verify that the result is 10.

-
調試應用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
-
-
在用戶被要求輸入之后,在
result = c.Calculate(x, oper, y);行上設置斷點。Set a breakpoint on theresult = 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.

現在,當我們調試程序時,它總是暫停該行的執行。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.
-
右鍵單擊表示斷點的紅點,並選擇“條件”。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.

現在,如果嘗試被 0 除,我們將在斷點處暫停執行。Now we pause execution at the breakpoint specifically if a division by 0 is attempted.
-
若要調試程序,請按 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:cinis smart enough to parse the input appropriately.

-
調試器中有用的窗口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. 顯示的“自動”窗口指示,在當前行之前,變量的當前值至少使用了三行。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.


也可將鼠標懸停在代碼本身中的變量上,以查看當前暫停執行的當前值。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.


繼續調試To continue debugging
-
-
左側的黃線表示當前的執行點。The yellow line on the left shows the current point of execution. 當前行調用
Calculate,因此按 F11 以“單步執行”函數。The current line callsCalculate, so press F11 to Step Into the function. 你會發現自己處於Calculate函數的主體中。You'll find yourself in the body of theCalculatefunction. 使用單步執行時請小心;如果使用次數過多,可能會浪費大量時間。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. -
現在執行點位於
Calculate函數的開頭,按 F10 移動到程序執行的下一行。Now that the point of execution is at the start of theCalculatefunction, 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 ofCalculate). -
繼續使用 F10 “單步跳過”每一行,直到返回到另一個文件中的
main()函數,然后停在cout行。Continue using F10 to Step Over each line until you get back to themain()function in the other file, and stop on thecoutline.看起來程序是在按預期執行操作:取第一個數字,然后除以第二個數字。It looks like the program is doing what is expected: it takes the first number, and divides it by the second. 在
cout行,將鼠標懸停在result變量上,或在“自動”窗口中查看result。On thecoutline, hover over theresultvariable or take a look atresultin 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 向前再執行一行時,控制台窗口將顯示以下內容:Thecoutline just outputs whatever value is stored inresult, so when you step one more line forward using F10, the console window displays:

發生這種情況是因為除以零未定義,因此程序無法給請求的操作提供數值解。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.
-
-
在 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):
C++// 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; } -
現在,按 F5 一次。Now press F5 once. 程序將繼續執行,直到它必須暫停以請求用戶輸入。Program execution continues all the way until it has to pause to ask for user input. 再次輸入
10 / 0。Enter10 / 0again. 現在,將輸出更有用的信息。Now, a more helpful message is printed. 用戶被要求輸入更多內容,程序繼續正常執行。The user is asked for more input, and the program continues executing normally.

備注
在調試模式下編輯代碼時,有可能會遇到舊代碼。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
了解有關 Visual Studio for C++ 的更多信息Learn more about Visual Studio for C++
創建 C++ 控制台應用項目Create a C++ console app project
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
-
- 在 Visual Studio 中安裝“使用 C++ 的桌面開發”工作負載並在計算機上運行。Have Visual Studio with the Desktop development with C++ workload installed and running on your computer. 如果尚未安裝,請參閱在 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.
-
-
在 Visual Studio 中的菜單欄上,選擇“文件” > “新建” > “項目”。On the menubar in Visual Studio, choose File > New > Project. 隨即將打開“新建項目”窗口。The New Project window opens.
-
在左側邊欄上,確保選中“Visual C++”。On the left sidebar, make sure Visual C++ is selected. 在中心,選擇“Windows 控制台應用程序”。In the center, choose Windows Console Application.
-
在底部的“名稱”編輯框中,將新項目命名為“CalculatorTutorial”,然后選擇“確定”。In the Name edit box at the bottom, name the new project CalculatorTutorial, then choose OK.


將創建一個空的 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:
C++// 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.
-
-
若要生成項目,請從“生成”菜單選擇“生成解決方案”。To build your project, choose Build Solution from the Build menu. “輸出”窗口將顯示生成過程的結果。The Output window shows the results of the build process.


-
若要運行代碼,請在菜單欄上選擇“調試”、“開始執行(不調試)”。To run the code, on the menu bar, choose Debug, Start without debugging.


隨即將打開控制台窗口,然后運行你的應用。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!
-
按任意鍵關閉該控制台窗口並返回到 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.
-
-
在“CalculatorTutorial.cpp”文件中,編輯代碼以匹配此示例:In the CalculatorTutorial.cpp file, edit the code to match this example:
C++// 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#includestatements 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 中為#include "stdafx.h")行引用名為預編譯標頭的內容。The#include "pch.h"(or in older versions of Visual Studio,#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++ 標准庫中的內容。Theusing 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 astd::, to denote its scope. 例如,如果沒有該行,則對cout的每個引用都必須寫為std::cout。For instance, without that line, each reference tocoutwould have to be written asstd::cout.using語句的使用是為了使代碼看起來更干凈。Theusingstatement is added to make the code look more clean.cout關鍵字用於在 C++ 中打印到標准輸出。Thecoutkeyword 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\ninside the string (contained by "") to do the same thing, asendlalways flushes the buffer and can hurt the performance of the program, but since this is a very small app,endlis used instead for better readability. - 所有 C++ 語句都必須以分號結尾,所有 C++ 應用程序都必須包含
main()函數。All C++ statements must end with semicolons and all C++ applications must contain amain()function. 該函數是程序開始運行時運行的函數。This function is what the program runs at the start. 若要使用所有代碼,必須可從main()訪問所有代碼。All code must be accessible frommain()in order to be used.
-
要保存文件,請輸入“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.
-
要運行該應用程序,請按“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.


-
完成后,請關閉控制台窗口。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
-
-
轉到“項目”菜單,並選擇“添加類”。Go to the Project menu and choose Add Class. 在“類名”編輯框中,輸入“Calculator”。In the Class Name edit box, enter Calculator. 選擇 “確定”。Choose OK. 這會向項目中添加兩個新文件。Two new files get added to your project. 若要同時保存所有已更改的文件,請按“Ctrl+Shift+S”。To save all your changed files at once, press Ctrl+Shift+S. 這是“文件” > “全部保存”的鍵盤快捷方式。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.


類就像執行某事的對象的藍圖。A class is like a blueprint for an object that does something. 在本示例中,我們定義了 Calculator 以及它的工作原理。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. 如果該窗口不可見,則可從菜單欄中打開它:選擇“查看” > “解決方案資源管理器”。If the window isn't visible, you can open it from the menu bar: choose View > Solution Explorer.


現在編輯器中應打開了三個選項卡:CalculatorTutorial.cpp、Calculator.h 和 Calculator.cpp。You 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.
-
在“Calculator.h”中,刪除生成的
Calculator();和~Calculator();行,因為在此處不需要它們。In Calculator.h, remove theCalculator();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:C++#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 calledCalculate, 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 theCalculatorclass separately from the file containing themain()function, but we plan to reference theCalculatorclass inmain().
- 所添加的行聲明了一個名為
-
你會看到
Calculate下顯示綠色波浪線。You'll see a green squiggle appear underCalculate. 因為我們還沒有在 .cpp 文件中定義Calculate函數。It's because we haven't defined theCalculatefunction 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.cpp”。The code was added to Calculator.cpp.

目前,它只返回 0.0。Currently, it just returns 0.0. 讓我們來更改它。Let's change that. 按 Esc 關閉彈出窗口。Press Esc to close the pop-up.
-
切換到編輯器窗口中的“Calculator.cpp”文件。Switch to the Calculator.cpp file in the editor window. 刪除
Calculator()和~Calculator()部分(就像在 .h 文件中一樣)並將以下代碼添加到Calculate():Remove theCalculator()and~Calculator()sections (as you did in the .h file) and add the following code toCalculate():C++#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 functionCalculateconsumes 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: case”是一個回滾,以防用戶鍵入一個不被接受的運算符,因此程序不會中斷。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關鍵字表示支持小數的數字類型。Thedoublekeyword denotes a type of number that supports decimals. 因此,Calculator 可以處理十進制數學和整數數學。This way, the calculator can handle both decimal math and integer math. 要始終返回這樣的數字,需要Calculate函數,因為代碼的最開始是double(這表示函數的返回類型),這就是為什么我們在默認情況下返回 0.0。TheCalculatefunction is required to always return such a number due to thedoubleat 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
-
-
現在讓我們更新“CalculatorTutorial.cpp”中的
main函數:Now let's update themainfunction in CalculatorTutorial.cpp:C++// 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 themain()function, we need to call our other code from there, so a#includestatement is needed. - 聲明了一些初始變量
x、y、oper和result,分別用於存儲第一個數字、第二個數字、運算符和最終結果。Some initial variablesx,y,oper, andresultare 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類的實例。TheCalculator c;line declares an object named 'c' as an instance of theCalculatorclass. 類本身只是計算器工作方式的藍圖;對象是進行數學運算的特定計算器。The class itself is just a blueprint for how calculators work; the object is the specific calculator that does the math.while (true)語句是一個循環。Thewhile (true)statement is a loop. 只要()內的條件成立,循環內的代碼就會一遍又一遍地執行。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 astrue, 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關鍵字用於接受來自用戶的輸入。Thecinkeyword 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 theCalculate()function would also need to be updated to handle this.c.Calculate(x, oper, y);表達式調用前面定義的Calculate函數,並提供輸入的輸入值。Thec.Calculate(x, oper, y);expression calls theCalculatefunction defined earlier, and supplies the entered input values. 然后該函數返回一個存儲在result中的數字。The function then returns a number that gets stored inresult.- 最后,將
result輸出到控制台,以便用戶查看計算結果。Finally,resultis printed to the console, so the user sees the result of the calculation.
- 由於 C++ 程序總是從
-
再次生成和測試代碼Build and test the code again
現在是時候再次測試程序以確保一切正常。Now it's time to test the program again to make sure everything works properly.
-
-
按“Ctrl+F5”重建並啟動應用。Press Ctrl+F5 to rebuild and start the app.
-
輸入
5 + 5,然后按 Enter。Enter5 + 5, and press Enter. 驗證結果是否為 10。Verify that the result is 10.

-
調試應用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
-
-
在用戶被要求輸入之后,在
result = c.Calculate(x, oper, y);行上設置斷點。Set a breakpoint on theresult = 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.

現在,當我們調試程序時,它總是暫停該行的執行。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.
-
右鍵單擊表示斷點的紅點,並選擇“條件”。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.

現在,如果嘗試被 0 除,我們將在斷點處暫停執行。Now we pause execution at the breakpoint specifically if a division by 0 is attempted.
-
若要調試程序,請按 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;cinis smart enough to parse the input appropriately.

-
調試器中有用的窗口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. 顯示的“自動”窗口指示,在當前行之前,變量的當前值至少使用了三行。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.


也可將鼠標懸停在代碼本身中的變量上,以查看當前暫停執行的當前值。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.


繼續調試To continue debugging
-
-
左側的黃線表示當前的執行點。The yellow line on the left shows the current point of execution. 當前行調用
Calculate,因此按 F11 以“單步執行”函數。The current line callsCalculate, so press F11 to Step Into the function. 你會發現自己處於Calculate函數的主體中。You'll find yourself in the body of theCalculatefunction. 使用單步執行時請小心;如果使用次數過多,可能會浪費大量時間。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. -
現在執行點位於
Calculate函數的開頭,按 F10 移動到程序執行的下一行。Now that the point of execution is at the start of theCalculatefunction, 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 ofCalculate). -
繼續使用 F10 “單步跳過”每一行,直到返回到另一個文件中的
main()函數,然后停在cout行。Continue using F10 to Step Over each line until you get back to themain()function in the other file, and stop on thecoutline.

看起來程序是在按預期執行操作:取第一個數字,然后除以第二個數字。It looks like the program is doing what is expected: it takes the first number, and divides it by the second. 在
cout行,將鼠標懸停在result變量上,或在“自動”窗口中查看result。On thecoutline, hover over theresultvariable or take a look atresultin 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 向前再執行一行時,控制台窗口將顯示以下內容:Thecoutline just outputs whatever value is stored inresult, so when you step one more line forward using F10, the console window displays:

發生這種情況是因為除以零未定義,因此程序無法給請求的操作提供數值解。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.
-
-
在 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):
C++// 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; } -
現在,按 F5 一次。Now press F5 once. 程序將繼續執行,直到它必須暫停以請求用戶輸入。Program execution continues all the way until it has to pause to ask for user input. 再次輸入
10 / 0。Enter10 / 0again. 現在,將輸出更有用的信息。Now, a more helpful message is printed. 用戶被要求輸入更多內容,程序繼續正常執行。The user is asked for more input, and the program continues executing normally.

備注
在調試模式下編輯代碼時,有可能會遇到舊代碼。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
了解有關 Visual Studio for C++ 的更多信息Learn more about Visual Studio for C++

