📄 ch02.htm
字号:
<TD ALIGN="LEFT" VALIGN="TOP"><B>Type</B></TD> <TD ALIGN="LEFT" VALIGN="TOP"><B>Size (in bytes)</B></TD> </TR> <TR ALIGN="LEFT" rowspan="1"> <TD ALIGN="LEFT" VALIGN="TOP"><TT>bool</TT></TD> <TD ALIGN="LEFT" VALIGN="TOP">1</TD> </TR> <TR ALIGN="LEFT" rowspan="1"> <TD ALIGN="LEFT" VALIGN="TOP"><TT>char</TT></TD> <TD ALIGN="LEFT" VALIGN="TOP">1</TD> </TR> <TR ALIGN="LEFT" rowspan="1"> <TD ALIGN="LEFT" VALIGN="TOP"><TT>short</TT></TD> <TD ALIGN="LEFT" VALIGN="TOP">2</TD> </TR> <TR ALIGN="LEFT" rowspan="1"> <TD ALIGN="LEFT" VALIGN="TOP"><TT>int</TT></TD> <TD ALIGN="LEFT" VALIGN="TOP">4</TD> </TR> <TR ALIGN="LEFT" rowspan="1"> <TD ALIGN="LEFT" VALIGN="TOP"><TT>long</TT></TD> <TD ALIGN="LEFT" VALIGN="TOP">4</TD> </TR> <TR ALIGN="LEFT" rowspan="1"> <TD ALIGN="LEFT" VALIGN="TOP"><TT>float</TT></TD> <TD ALIGN="LEFT" VALIGN="TOP">4</TD> </TR> <TR ALIGN="LEFT" rowspan="1"> <TD ALIGN="LEFT" VALIGN="TOP"><TT>double</TT></TD> <TD ALIGN="LEFT" VALIGN="TOP">8</TD> </TR> <TR ALIGN="LEFT" rowspan="1"> <TD ALIGN="LEFT" VALIGN="TOP"><TT>long double</TT></TD> <TD ALIGN="LEFT" VALIGN="TOP">8</TD> </TR></TABLE><H3><FONT COLOR="#000077"><B>Variable Naming</B></FONT></H3><P>One important part of programming is the selection of names for your variablesand other parts of your programs. The program listings you've seen so far have beenvery simple. As you become a more experienced user of Visual C++, you will need toestablish some sort of naming convention for your identifiers.</P><P>When naming your variables, use names that are as long as necessary to indicatehow the variable is used. A variable name in C++ is an example of an identifier.Identifiers in C++ are used to name variables and functions, among other things.In Visual C++, your identifiers can be literally hundreds of characters long andcan include any combination of letters, numbers, and underscores, as long as thefirst character is a letter or underscore. Listing 2.3 is an example of several differentvariable declarations.<H4><FONT COLOR="#000077">TYPE: Listing 2.3. Some examples of good and bad variablenames.</FONT></H4><PRE><FONT COLOR="#0066FF"><TT>#include <iostream></TT><TT>using namespace std;</TT><TT>int main()</TT><TT>{</TT><TT> // Good declarations</TT><TT> int nEmployees; // Number of employees</TT><TT> char chMiddleInitial; // A middle initial</TT><TT> // Declarations that could be improved</TT><TT> int i, n, k; // What are these vars used for ?</TT><TT> float temp; // May not be enough information</TT><TT> char ch; // Should have more information</TT><TT> return 0;</TT><TT>}</TT></FONT></PRE><P>No matter which technique you use to name your variables, it's important to beconsistent. For example, most of the sample programs and online help examples providedas part of Visual C++ use a naming convention known as <I>Hungarian Notation</I>.</P><P>When Hungarian is used properly, it's easy to tell the logical type of variableat a glance without searching for its declaration. For example, most scalar variablessuch as <TT>int</TT>, <TT>long</TT>, or <TT>short</TT> are prefixed with an <TT>n</TT>.Variables that are used to store characters are prefixed with <TT>ch</TT>, as in<TT>chEntry</TT> and <TT>chInitial</TT>. Most of the sample code available from Microsoftuses Hungarian Notation, which will be used for the remainder of the code listingsin this book. A listing of common Hungarian prefixes is provided in Appendix D, "HungarianNotation."<BLOCKQUOTE> <P><HR><FONT COLOR="#000077"><B>DO/DON'T:</B></FONT><B> <BR> DO</B> use meaningful names for your variables.<BR> <B>DO</B> be consistent in your naming conventions.<BR> <B>DO</B> use variable types that match your data.<BR> <B>DON'T</B> depend on capitalization to differentiate between variables. <HR></BLOCKQUOTE><H3><FONT COLOR="#000077"><B>Assigning Values to Variables</B></FONT></H3><P>In assigning values to variables, the assignment operator is just an equals signused as follows:</P><PRE><FONT COLOR="#0066FF"><TT>nFoo = 42;</TT></FONT></PRE><P>This line assigns the integer value <TT>42</TT> to <TT>nFoo</TT>.</P><P>If a floating-point decimal value is assigned, it's assumed by the compiler tobe a <TT>double</TT>, as follows:</P><PRE><FONT COLOR="#0066FF"><TT>dFoo = 42.4242;</TT></FONT></PRE><P>You can assign to a variable of type <TT>char</TT> in two ways. If you are actuallystoring a character value, you can assign the letter using single quotes as shownhere:</P><PRE><FONT COLOR="#0066FF"><TT>chInitial = `Z';</TT></FONT></PRE><P>The compiler converts the letter value into an ASCII value and stores it in the<TT>char</TT> variable. Small integer values can also be stored in a <TT>char</TT>,and the assignment is done just like an <TT>int</TT> variable.</P><PRE><FONT COLOR="#0066FF"><TT>chReallyAnInt = 47; </TT></FONT></PRE><BLOCKQUOTE> <P><HR><FONT COLOR="#000077"><B>Time Saver:</B></FONT><B> </B>The <TT>char</TT> variable type is sometimes used to store small integer values. This is useful if you are storing a large number of values, because an <TT>int</TT> takes up four times the storage of a <TT>char</TT>. <HR></BLOCKQUOTE><H2><FONT COLOR="#000077"><B>A Simple C++ Program</B></FONT></H2><P>In Hour 1, you created a C++ project named Hello that displayed a simple "HelloWorld!" message. This hour you will make a simple modification to the Helloproject--the Hello2 project will ask you for a name and then use the name in thegreeting. Building this project will help demonstrate some common elements foundin C++ programs.<H3><FONT COLOR="#000077"><B>Creating the Hello2 Project</B></FONT></H3><P>The first step in writing any Visual C++ program is to create a project, as youdid in the first hour. To review, these are the steps required to create a console-modeproject:<DL> <DD>1. Begin by selecting File | New from the Visual C++ main menu. This will display the New dialog box.<BR> <BR> 2. Select the Projects tab in the New dialog box. A list box containing different types of projects will be displayed.<BR> <BR> 3. Select the icon labeled Win32 Console Application, as shown in Figure 2.2. You must also provide a name for the project--a default location will be provided for you automatically.</DL><P><A NAME="02"></A><A HREF="02.htm"><B>Figure 2.2.</B> </A><I><BR>The New Projects dialog box.</I></P><P>After you have selected the project type and the subdirectory, click OK to createthe project.<H3><FONT COLOR="#000077"><B>Creating the Source File for Your Program</B></FONT></H3><P>The source file for the Hello2 project is shown in Listing 2.4. Unlike your firstHello program, this version collects input from the user and then outputs a greeting.<H4><FONT COLOR="#000077">TYPE: Listing 2.4. A console mode program that acceptsinput.</FONT></H4><PRE><FONT COLOR="#0066FF"><TT>#include <iostream></TT><TT>#include <string></TT><TT>using namespace std;</TT><TT>// Prompt the user to enter a name, collect the name,</TT><TT>// and display a message to the user that contains</TT><TT>// the name.</TT><TT>int main()</TT><TT>{</TT><TT> string userName;</TT><TT> cout << "What is your name? :";</TT><TT> cin >> userName;</TT><TT> cout << "Hello " << userName << "!" << endl;</TT><TT> return 0;</TT><TT>}</TT></FONT></PRE><P>Open a new C++ source file and type the code shown in Listing 2.4. Remember thatC++ is case-sensitive. Save the file as <TT>Hello2.cpp</TT> in the project's directory.To review, these are the steps required to open a new C++ source file and add itto the project:<DL> <DD>1. Select File | New from the main menu, and select the Files tab in the New dialog box.<BR> <BR> 2. Select the icon labeled C++ Source File.<BR> <BR> 3. Check the Add to Project check box, and enter <TT>Hello2.cpp</TT> as the filename.<BR> <BR> 4. Click OK to close the dialog box and open the file for editing.</DL><P>Compile the Hello2 project by selecting Build | Build Hello2.exe from the mainmenu (or press F7). If the source code was entered correctly, the project will bebuilt with no errors, and the last line in the status window will read</P><PRE><FONT COLOR="#0066FF"><TT>Hello2.exe - 0 error(s), 0 warning(s)</TT></FONT></PRE><P>If there are errors or warnings, check the source code for typographical errorsand build again.<H3><FONT COLOR="#000077"><B>Running the Hello2 Program</B></FONT></H3><P>Open a DOS window and change to the <TT>DEBUG</TT> subdirectory under the Hello2project directory. Run the Hello2 program by typing <TT>Hello2</TT> at the DOS prompt.The program produces the following output:</P><PRE><FONT COLOR="#0066FF"><TT>What is your name? :Alex</TT><TT>Hello Alex!</TT></FONT></PRE><P>The Hello2 program accepts any name as input and uses that name for its HelloWorld message.<H3><FONT COLOR="#000077"><B>Analyzing the Hello2 Program</B></FONT></H3><P>Let's take a look at the Hello2 program because it has a lot in common with muchlarger C++ programs. Even though it is fairly short, it has many of the elementsthat you will see in more complicated Windows programs later in this book.<H4><FONT COLOR="#000077">Include Statements</FONT></H4><P>The first line of <TT>Hello2.cpp</TT> is a message to the compiler to includeanother file when compiling <TT>Hello2.cpp</TT>:</P><PRE><FONT COLOR="#0066FF"><TT>#include <iostream></TT></FONT></PRE><P>This <TT>#include</TT> statement tells the compiler to look for the file named<TT>iostream</TT> and insert it into your source file. Actually, the <TT>#include</TT>statement is read by the preprocessor, a part of the compiler that scans the sourcefile before the file is compiled.</P><P><FONT COLOR="#000077"><B>New Term:</B></FONT><B> </B>Statements read by the preprocessorare known as <I>preprocessor directives</I> because they aren't actually used bythe compiler. Preprocessor directives always begin with a <TT>#</TT>. You will learnmore about preprocessor statements throughout the rest of the book.</P><P><FONT COLOR="#000077"><B>New Term:</B></FONT><B> </B>The file <TT>iostream</TT>is an example of a <I>header</I> file. A header file contains declarations or othercode used to compile your program. In order to perform common input and output operations,you must <TT>#include</TT> the <TT>iostream</TT> file.<BLOCKQUOTE> <P><HR><B> </B><FONT COLOR="#000077"><B>Just a Minute:</B></FONT><B> </B>Traditionally, C++ header files have an <TT>.h</TT> or <TT>.hpp</TT> file extension; the standard C++ library includes files such as <TT>iostream</TT> that have no extension. For backward compatibility, the Visual C++ compiler includes older versions of the include files that have the <TT>.h</TT> extension. <HR></BLOCKQUOTE><P>The <TT>#include</TT> preprocessor directive is seen in two basic forms:
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -