祝贺你! 你已经完成计算器应用的代码,并在 Visual Studio 中生成和调试了该代码。
本文内容
创建 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#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++ 标准库中的内容。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 tocout
would have to be written asstd::cout
.using
语句的使用是为了使代码看起来更干净。Theusing
statement is added to make the code look more clean.cout
关键字用于在 C++ 中打印到标准输出。Thecout
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, asendl
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 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 theCalculator
class separately from the file containing themain()
function, but we plan to reference theCalculator
class inmain()
.
- 所添加的行声明了一个名为
-
你会看到
Calculate
下显示绿色波浪线。You'll see a green squiggle appear underCalculate
. 因为我们还没有在 .cpp 文件中定义Calculate
函数。It's because we haven't defined theCalculate
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.随即将出现一个弹出窗口,可在其中查看在另一个文件中进行的代码更改。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 functionCalculate
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: 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
关键字表示支持小数的数字类型。Thedouble
keyword 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。TheCalculate
function is required to always return such a number due to thedouble
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
-
现在让我们更新“CalculatorTutorial.cpp”中的
main
函数:Now let's update themain
function 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#include
statement is needed. - 声明了一些初始变量
x
、y
、oper
和result
,分别用于存储第一个数字、第二个数字、运算符和最终结果。Some initial variablesx
,y
,oper
, andresult
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
类的实例。TheCalculator c;
line declares an object named 'c' as an instance of theCalculator
class. 类本身只是计算器工作方式的蓝图;对象是进行数学运算的特定计算器。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
关键字用于接受来自用户的输入。Thecin
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 theCalculate()
function would also need to be updated to handle this.c.Calculate(x, oper, y);
表达式调用前面定义的Calculate
函数,并提供输入的输入值。Thec.Calculate(x, oper, y);
expression calls theCalculate
function defined earlier, and supplies the entered input values. 然后该函数返回一个存储在result
中的数字。The function then returns a number that gets stored inresult
.- 最后,将
result
输出到控制台,以便用户查看计算结果。Finally,result
is 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:cin
is 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 theCalculate
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. -
现在执行点位于
Calculate
函数的开头,按 F10 移动到程序执行的下一行。Now that the point of execution is at the start of theCalculate
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 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 thecout
line.看起来程序是在按预期执行操作:取第一个数字,然后除以第二个数字。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 thecout
line, hover over theresult
variable or take a look atresult
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 向前再执行一行时,控制台窗口将显示以下内容:Thecout
line 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 / 0
again. 现在,将输出更有用的信息。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#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 中为#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 tocout
would have to be written asstd::cout
.using
语句的使用是为了使代码看起来更干净。Theusing
statement is added to make the code look more clean.cout
关键字用于在 C++ 中打印到标准输出。Thecout
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, asendl
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 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 theCalculator
class separately from the file containing themain()
function, but we plan to reference theCalculator
class inmain()
.
- 所添加的行声明了一个名为
-
你会看到
Calculate
下显示绿色波浪线。You'll see a green squiggle appear underCalculate
. 因为我们还没有在 .cpp 文件中定义Calculate
函数。It's because we haven't defined theCalculate
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.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 functionCalculate
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: 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
关键字表示支持小数的数字类型。Thedouble
keyword 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。TheCalculate
function is required to always return such a number due to thedouble
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
-
现在让我们更新“CalculatorTutorial.cpp”中的
main
函数:Now let's update themain
function 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#include
statement is needed. - 声明了一些初始变量
x
、y
、oper
和result
,分别用于存储第一个数字、第二个数字、运算符和最终结果。Some initial variablesx
,y
,oper
, andresult
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
类的实例。TheCalculator c;
line declares an object named 'c' as an instance of theCalculator
class. 类本身只是计算器工作方式的蓝图;对象是进行数学运算的特定计算器。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
关键字用于接受来自用户的输入。Thecin
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 theCalculate()
function would also need to be updated to handle this.c.Calculate(x, oper, y);
表达式调用前面定义的Calculate
函数,并提供输入的输入值。Thec.Calculate(x, oper, y);
expression calls theCalculate
function defined earlier, and supplies the entered input values. 然后该函数返回一个存储在result
中的数字。The function then returns a number that gets stored inresult
.- 最后,将
result
输出到控制台,以便用户查看计算结果。Finally,result
is 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;cin
is 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 theCalculate
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. -
现在执行点位于
Calculate
函数的开头,按 F10 移动到程序执行的下一行。Now that the point of execution is at the start of theCalculate
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 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 thecout
line.看起来程序是在按预期执行操作:取第一个数字,然后除以第二个数字。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 thecout
line, hover over theresult
variable or take a look atresult
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 向前再执行一行时,控制台窗口将显示以下内容:Thecout
line 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 / 0
again. 现在,将输出更有用的信息。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++