⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 ch02.htm

📁 24小时学会vc++
💻 HTM
📖 第 1 页 / 共 3 页
字号:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN"><HTML><HEAD>		<TITLE>Teach Yourself Visual C++&#174; 5 in 24 Hours -- Hour 2 -- Writing Simple C++ Programs</TITLE></HEAD><BODY TEXT="#000000" BGCOLOR="#FFFFFF"><CENTER><H1><IMG SRC="../button/sams.gif" WIDTH="171" HEIGHT="66" ALIGN="BOTTOM" BORDER="0"><BR><FONT COLOR="#000077">Teach Yourself Visual C++&#174; 5 in 24 Hours</FONT></H1></CENTER><CENTER><P><A HREF="../ch01/ch01.htm"><IMG SRC="../button/previous.gif" WIDTH="128" HEIGHT="28"ALIGN="BOTTOM" ALT="Previous chapter" BORDER="0"></A><A HREF="../ch03/ch03.htm"><IMGSRC="../button/next.gif" WIDTH="128" HEIGHT="28" ALIGN="BOTTOM" ALT="Next chapter"BORDER="0"></A><A HREF="../index.htm"><IMG SRC="../button/contents.gif" WIDTH="128"HEIGHT="28" ALIGN="BOTTOM" ALT="Contents" BORDER="0"></A> <HR></CENTER><CENTER><H1><FONT COLOR="#000077">- Hour 2 -<BR>Writing Simple C++ Programs</FONT></H1></CENTER><P>In the previous hour, you compiled some simple programs. Now it's time to learnsome more details about how C++ programs work. Even simple C++ programs demonstratebasic concepts that are shared by all applications.</P><P>In this hour, you will learn<UL>	<LI>The common elements of a C++ program<BR>	<BR>		<LI>Standard input and output in a C++ program<BR>	<BR>		<LI>The C++ preprocessor</UL><P>In this hour you will build a simple C++ program that accepts input from the userand echoes it back on the screen.<H2><FONT COLOR="#000077"><B>The Common Elements of a C++ Program</B></FONT></H2><P>Computer programs are composed of instructions and data. Instructions tell thecomputer to do things, such as to add and subtract. Data is what the computer operateson, such as the numbers that are added and subtracted. In mature programs, the instructionsdon't change as the program executes (at least they're not supposed to). Data, onthe other hand, can and usually does change or vary as the program executes. A variableis nothing more than the name used to point to a piece of this data.<H3><FONT COLOR="#000077"><B>Fundamental C++ Data Types</B></FONT></H3><P>The C++ language offers several fundamental data types. As in most other programminglanguages, these built-in types are used to store and calculate data used in yourprogram. In later chapters, you use these fundamental types as a starting point foryour own more complex data types.</P><P>C++ has a strong type system, which is used to make sure that your data variablesare used consistently and correctly. This makes it easy for the compiler to detecterrors in your program when it is compiled rather than when it is executing. Beforea variable is used in C++, it must first be declared and defined as follows:</P><PRE><FONT COLOR="#0066FF"><TT>int    myAge;</TT></FONT></PRE><P>This line declares and defines a variable named <TT>myAge</TT> as an integer.A declaration introduces the name <TT>myAge</TT> to the compiler and attaches a specificmeaning to it. A definition like this also instructs the compiler to allocate memoryand create the variable or other object.</P><P>When the Visual C++ compiler reads the <TT>myAge</TT> definition, it will do thefollowing:<UL>	<LI>Set aside enough memory storage for an integer and use the name <TT>myAge</TT>	to refer to it<BR>	<BR>		<LI>Reserve the name <TT>myAge</TT> so that it isn't used by another variable<BR>	<BR>		<LI>Ensure that whenever <TT>myAge</TT> is used, it is used in a way that is consistent	with the way an integer should be used</UL><BLOCKQUOTE>	<P><HR><B> </B><FONT COLOR="#000077"><B>Time Saver:</B></FONT><B> </B>It's possible to define	several variables on a single line, although as a style issue, many people prefer	to declare one variable per line. If you want to make your source file more compact,	you can separate your variables by a comma, as follows:</P>	<PRE><FONT COLOR="#0066FF"><TT>int    myAge, yourAge, maximumAge;</TT></FONT></PRE>	<P>This line defines three integer variables. Declaring all three variables on one	line of code doesn't make your code execute any faster, but it can sometimes help	make your source code more readable. <HR></BLOCKQUOTE><H3><FONT COLOR="#000077"><B>Understanding Type Safety</B></FONT></H3><P><FONT COLOR="#000077"><B>New Term:</B></FONT><B> </B>Some languages enable youto use variables without declaring them. This often leads to problems that are difficultto trace or fix. When using C++, you must declare all variables before they are used.This enables the compiler to catch most of the common errors in your software program.This capability to catch errors when your program is compiled is sometimes referredto as <I>type safety</I>.</P><P>You can think of type safety as a warranty that the compiler helps to enforcein your C++ program. For example, if you try to use an <TT>int</TT> when anothertype is expected, the compiler either complains or converts the variable into theexpected type. If no conversion is possible, the compiler generates an error andyou have to correct the problem before the program can be compiled.</P><P>For example, character values are normally between 0 and 127 and are stored invariables of type <TT>char</TT>. In Visual C++, a <TT>char</TT> is a single bytevariable and is quite capable of storing all character values. If the compiler detectsthat you are attempting to store a number larger than 127 in a <TT>char</TT>, itwill complain about it and issue a warning message. Listing 2.1 is an example ofa program that tries to store a value that is too large in a <TT>char</TT>.<H4><FONT COLOR="#000077">TYPE: Listing 2.1. An example of a problem that can becaught by the compiler.</FONT></H4><PRE><FONT COLOR="#0066FF"><TT>#include &lt;iostream&gt;</TT><TT>using namespace std;</TT><TT>// This program will generate a compiler warning</TT><TT>int main()</TT><TT>{</TT><TT>    char distance = 765;</TT><TT>    cout &lt;&lt; &quot;The distance is &quot; &lt;&lt; distance &lt;&lt; endl;</TT><TT>    return 0;</TT><TT>}</TT></FONT></PRE><P>To see an example of a type mismatch that is caught by the compiler, create aconsole mode project with Listing 2.1 as the only source file, following the stepsused in Hour 1, &quot;Introducing Visual C++ 5.&quot; The compiler flags line 6 witha warning; however, it still generates an executable program.</P><P>In order to get the program to compile with no warnings and run as expected, youmust change line 5 so that the distance variable is defined as an integer:</P><PRE><FONT COLOR="#0066FF"><TT>int distance = 765;</TT></FONT></PRE><P>The new version of the source code is shown in Listing 2.2.<H4><FONT COLOR="#000077">TYPE: Listing 2.2. A corrected version of the previousexample.</FONT></H4><PRE><FONT COLOR="#0066FF"><TT>#include &lt;iostream&gt;</TT><TT>using namespace std;</TT><TT>// This program will compile properly.</TT><TT>int main()</TT><TT>{</TT><TT>    int distance = 765;</TT><TT>    cout &lt;&lt; &quot;The distance is &quot; &lt;&lt; distance &lt;&lt; endl;</TT><TT>    return 0;</TT><TT>}</TT></FONT></PRE><P><FONT COLOR="#000077"><B>New Term:</B></FONT><B> </B>Another common data typeis the <I>floating-point value</I>, or a number with a decimal point. Floating-pointvalues are stored in <TT>float</TT> or <TT>double</TT> variables in C++ programs.These are the only two built-in (or fundamental) variable types that can store floating-pointvalues.<H3><FONT COLOR="#000077"><B>Using Different Variable Types</B></FONT></H3><P>So far, you've used <TT>int</TT> and <TT>double</TT> variables, two of the fundamentaltypes available in C++. They're called fundamental types because they are the basicdata types that are a part of the language definition. There is also a set of derivedtypes that will be covered in the next few hours. In addition, as you saw earlierwith the string class, you can define your own types that work just like the built-intypes. The names of the built-in types used in C++ include the following:<UL>	<LI><TT>bool</TT> is a Boolean variable that can have the values <TT>true</TT> or	<TT>false</TT>.<BR>	<BR>		<LI><TT>char</TT> is a variable normally used for storing characters. In Visual C++,	it can have any value from -128 to 127. If <TT>char</TT> is declared as <TT>unsigned</TT>,	its range is from 0 to 255, and no negative values are allowed.<BR>	<BR>		<LI>A <TT>short int</TT> variable, sometimes just written as <TT>short</TT>, is similar	to an <TT>int</TT>, but it can contain a smaller range of values. Think of it as	a lightweight version of an <TT>int</TT> that can be used if data storage is a problem.	A <TT>short</TT> variable can store any scalar (whole) value between -32768 and 32767.	If a <TT>short</TT> is declared as <TT>unsigned</TT>, its range is from 0 to 65535.<BR>	<BR>		<LI><TT>int</TT> is an integer value used to store whole numbers. When using Visual	C++, an <TT>int</TT> is a 32-bit value so it can store any value from -2,147,483,648	to 2,147,483,647. If an <TT>int</TT> is declared as <TT>unsigned</TT>, its range	is from 0 to 4,294,967,295.<BR>	<BR>		<LI>A <TT>long int</TT>, sometimes just written as <TT>long</TT>, is a scalar variable	like an <TT>int</TT>, only larger when using some compilers. In Visual C++, a <TT>long	int</TT> can store the same values as an <TT>int</TT>.<BR>	<BR>		<LI>A <TT>float</TT> variable is the smallest variable type capable of storing floating-point	values. It is often an approximation of the value that was originally stored. In	Visual C++, a <TT>float</TT> stores up to six decimal digits.<BR>	<BR>		<LI>A <TT>double</TT> variable stores floating-point values just like a <TT>float</TT>	does. However, the compiler stores the value with more precision, meaning that a	more accurate value can be stored. A <TT>double</TT> can store up to 15 decimal digits.<BR>	<BR>		<LI>A <TT>long double</TT> has the same characteristics as a <TT>double</TT>. However,	from the compiler's point of view, they are different types. The <TT>long double</TT>	type is part of the C++ language, and on some machines and compilers, the difference	between <TT>double</TT> and <TT>long double</TT> is that <TT>long double</TT> has	greater precision, allowing storage of more than 15 decimal digits.</UL><P><FONT COLOR="#000077"><B>New Term:</B></FONT><B> </B>Some of the variables inthe preceding list can be declared as <I>unsigned</I>. When a variable is declaredas unsigned, it can store only non-negative values. When a variable is declared asan <TT>int</TT>, it can store both negative and positive numbers. However, an <TT>unsignedint</TT> can store a much larger positive value than a plain old <TT>int</TT>.</P><P>An <TT>unsigned int </TT>can store a larger positive value because the computermust use one bit of data in the memory location to handle the sign. This sign indicateswhether the variable is positive or negative. Because using the sign bit reducesthe number of bits that are available for storage, the maximum value for the variableis reduced by half. Figure 2.1 is an example of a variable that has been declaredas <TT>int</TT> and another variable that has been declared as <TT>unsigned int</TT>.</P><P><A NAME="01"></A><A HREF="01.htm"><B>Figure 2.1.</B></A> <I><BR>Most computers can use a sign bit to determine whether a variable is positive ornegative.</I></P><P>The fundamental variable types require different amounts of storage. As a ruleof thumb, the <TT>char</TT> data type is large enough to contain all the charactersin the machine's native language, or eight bits. The <TT>int</TT> type is usuallythe &quot;natural&quot; variable size for the target machine, so <TT>int</TT> variablesare 32 bits in Visual C++. Table 2.1 lists the number of bytes required to storeeach of the fundamental types.<BLOCKQUOTE>	<P><HR><B> </B><FONT COLOR="#000077"><B>Just a Minute:</B></FONT><B> </B>Earlier versions	of Visual C++ that were used with Windows 3.1 were 16-bit compilers. The natural	variable size under Windows 3.1 was 16 bits, so the <TT>int</TT> type was 16 bits.	The last version of Visual C++ that used 16-bit integers was Visual C++ 1.5. <HR></BLOCKQUOTE><H4><FONT COLOR="#000077">Table 2.1. Storage required for fundamental C++ types.</FONT></H4><P><TABLE BORDER="1">	<TR ALIGN="LEFT" rowspan="1">

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -