📄 ch21.htm
字号:
48: else
49: cout << "Jim is full time" << endl;
50:
51: Jim.SetStatus(PartTime);
52:
53: if (Jim.GetStatus())
54: cout << "Jim is part time" << endl;
55: else
56: cout << "Jim is full time" << endl;
57:
58: cout << "Jim is on the " ;
59:
60: char Plan[80];
61: switch (Jim.GetPlan())
62: {
63: case OneMeal: strcpy(Plan,"One meal"); break;
64: case AllMeals: strcpy(Plan,"All meals"); break;
65: case WeekEnds: strcpy(Plan,"Weekend meals"); break;
66: case NoMeals: strcpy(Plan,"No Meals");break;
67: default : cout << "Something bad went wrong!\n"; break;
68: }
69: cout << Plan << " food plan." << endl;
70: return 0;
<TT>71: }</TT></FONT>
<FONT COLOR="#0066FF">
Output: Jim is part time
Jim is full time
Jim is on the No Meals food plan.
</FONT></PRE>
<P><FONT COLOR="#000077"><B>Analysis:</B></FONT><B> </B>On lines 3 to 7, several
enumerated types are defined. These serve to define the possible values for the bit
fields within the student class.<BR>
<TT><BR>
Student</TT> is declared in lines 8-27. While this is a trivial class, it is interesting
in that all the data is packed into five bits. The first bit represents the student's
status, full-time or part-time. The second bit represents whether or not this is
an undergraduate. The third bit represents whether or not the student lives in a
dorm. The final two bits represent the four possible food plans.</P>
<P>The class methods are written as for any other class, and are in no way affected
by the fact that these are bit fields and not integers or enumerated types.</P>
<P>The member function <TT>GetStatus()</TT> reads the Boolean bit and returns an
enumerated type, but this is not necessary. It could just as easily have been written
to return the value of the bit field directly. The compiler would have done the translation.</P>
<PRE>To prove that to yourself, replace the <TT>GetStatus()</TT> implementation with this code:</PRE>
<PRE><FONT COLOR="#0066FF">STATUS student::GetStatus()
{
return myStatus;
}</FONT></PRE>
<P>There should be no change whatsoever to the functioning of the program. It is
a matter of clarity when reading the code; the compiler isn't particular.</P>
<P>Note that the code on line 46 must check the status and then print the meaningful
message. It is tempting to write this:</P>
<PRE><FONT COLOR="#0066FF">cout << "Jim is " << Jim.GetStatus() << endl;</FONT></PRE>
<P>That will simply print this:</P>
<PRE><FONT COLOR="#0066FF">Jim is 0</FONT></PRE>
<P>The compiler has no way to translate the enumerated constant <TT>PartTime</TT>
into meaningful text.</P>
<P>On line 61, the program switches on the food plan, and for each possible value
it puts a reasonable message into the buffer, which is then printed on line 69. Note
again that the <TT>switch</TT> statement could have been written as follows:</P>
<PRE><FONT COLOR="#0066FF">case 0: strcpy(Plan,"One meal"); break;
case 1: strcpy(Plan,"All meals"); break;
case 2: strcpy(Plan,"Weekend meals"); break;
case 3: strcpy(Plan,"No Meals");break;</FONT></PRE>
<P>The most important thing about using bit fields is that the client of the class
need not worry about the data storage implementation. Because the bit fields are
private, you can feel free to change them later and the interface will not need to
change.
<CENTER>
<H3><A NAME="Heading30"></A><FONT COLOR="#000077">Style</FONT></H3>
</CENTER>
<P>As stated elsewhere in this book, it is important to adopt a consistent coding
style, though in many ways it doesn't matter which style you adopt. A consistent
style makes it easier to guess what you meant by a particular part of the code, and
you avoid having to look up whether you spelled the function with an initial cap
or not the last time you invoked it.</P>
<P>The following guidelines are arbitrary; they are based on the guidelines used
in projects I've worked on in the past, and they've worked well. You can just as
easily make up your own, but these will get you started.</P>
<P>As Emerson said, "Foolish consistency is the hobgoblin of small minds,"
but having some consistency in your code is a good thing. Make up your own, but then
treat it as if it were dispensed by the programming gods.
<CENTER>
<H4><A NAME="Heading31"></A><FONT COLOR="#000077">Indenting</FONT></H4>
</CENTER>
<P>Tab size should be four spaces. Make sure your editor converts each tab to four
spaces.
<CENTER>
<H4><A NAME="Heading32"></A><FONT COLOR="#000077">Braces</FONT></H4>
</CENTER>
<P>How to align braces can be the most controversial topic between C and C++ programmers.
Here are the tips I suggest:
<UL>
<LI>Matching braces should be aligned vertically.
<P>
<LI>The outermost set of braces in a definition or declaration should be at the left
margin. Statements within should be indented. All other sets of braces should be
in line with their leading statements.
<P>
<LI>No code should appear on the same line as a brace. For example:
</UL>
<PRE><FONT COLOR="#0066FF">if (condition==true)
{
j = k;
SomeFunction();
}
m++;
</FONT></PRE>
<CENTER>
<H4><A NAME="Heading33"></A><FONT COLOR="#000077">Long Lines</FONT></H4>
</CENTER>
<P>Keep lines to the width displayable on a single screen. Code that is off to the
right is easily overlooked, and scrolling horizontally is annoying. When a line is
broken, indent the following lines. Try to break the line at a reasonable place,
and try to leave the intervening operator at the end of the previous line (as opposed
to the beginning of the following line) so that it is clear that the line does not
stand alone and that there is more coming.</P>
<P>In C++, functions tend to be far shorter than they were in C, but the old, sound
advice still applies. Try to keep your functions short enough to print the entire
function on one page.
<CENTER>
<H4><A NAME="Heading34"></A><FONT COLOR="#000077">switch Statements</FONT></H4>
</CENTER>
<P>Indent switches as follows to conserve horizontal space:</P>
<PRE><FONT COLOR="#0066FF">switch(variable)
{
case ValueOne:
ActionOne();
break;
case ValueTwo:
ActionTwo();
break;
default:
assert("bad Action");
break;
}
</FONT></PRE>
<CENTER>
<H4><A NAME="Heading35"></A><FONT COLOR="#000077">Program Text</FONT></H4>
</CENTER>
<P>There are several tips you can use to create code that is easy to read. Code that
is easy to read is easy to maintain.
<UL>
<LI>Use whitespace to help readability.
<P>
<LI>Objects and arrays are really referring to one thing. Don't use spaces within
object references (<TT>.</TT>, <TT>-></TT>, <TT>[]</TT>).
<P>
<LI>Unary operators are associated with their operands, so don't put a space between
them. Do put a space on the side away from the operand. Unary operators include <TT>!</TT>,
<TT>~</TT>, <TT>++</TT>, <TT>--</TT>, <TT>-</TT>, <TT>*</TT> (for pointers), <TT>&</TT>
(casts), <TT>sizeof</TT>.
<P>
<LI>Binary operators should have spaces on both sides: <TT>+</TT>, <TT>=</TT>, <TT>*</TT>,
<TT>/</TT>, <TT>%</TT>, <TT>>></TT>, <TT><<</TT>, <TT><</TT>, <TT>></TT>,
<TT>==</TT>, <TT>!=</TT>, <TT>&</TT>, <TT>|</TT>, <TT>&&</TT>, <TT>||</TT>,
<TT>?:</TT>, <TT>=</TT>, <TT>+=</TT>, and so on.
<P>
<LI>Don't use lack of spaces to indicate precedence (<TT>4+ 3*2</TT>).
<P>
<LI>Put a space after commas and semicolons, not before.
<P>
<LI>Parentheses should not have spaces on either side.
<P>
<LI>Keywords, such as <TT>if</TT>, should be set off by a space: <TT>if (a == b)</TT>.
<P>
<LI>The body of a comment should be set off from the <TT>//</TT> with a space.
<P>
<LI>Place the pointer or reference indicator next to the type name, not the variable
name:
</UL>
<PRE><FONT COLOR="#0066FF">char* foo;
int& theInt;
</FONT></PRE>
<UL>
<LI>rather than
</UL>
<PRE><FONT COLOR="#0066FF">char *foo;
int &theInt;
</FONT></PRE>
<UL>
<LI>Do not declare more than one variable on the same line.
</UL>
<CENTER>
<H4><A NAME="Heading36"></A><FONT COLOR="#000077">Identifier Names</FONT></H4>
</CENTER>
<P>Here are some guidelines for working with identifiers.
<UL>
<LI>Identifier names should be long enough to be descriptive.
<P>
<LI>Avoid cryptic abbreviations.
<P>
<LI>Take the time and energy to spell things out.
<P>
<LI>Do not use Hungarian notation. C++ is strongly typed and there is no reason to
put the type into the variable name. With user-defined types (classes), Hungarian
notation quickly breaks down. The exceptions to this may be to use a prefix for pointers
(<TT>p</TT>) and references (<TT>r</TT>), as well as for class member variables (<TT>its</TT>).
<P>
<LI>Short names (<TT>i</TT>, <TT>p</TT>, <TT>x</TT>, and so on) should only be used
where their brevity makes the code more readable and where the usage is so obvious
that a descriptive name is not needed.
<P>
<LI>The length of a variable's name should be proportional to its scope.
<P>
<LI>Make sure identifiers look and sound different from one another to minimize confusion.
<P>
<LI>Function (or method) names are usually verbs or verb-noun phrases: <TT>Search()</TT>,
<TT>Reset()</TT>, <TT>FindParagraph()</TT>, <TT>ShowCursor()</TT>. Variable names
are usually abstract nouns, possibly with an additional noun: <TT>count</TT>, <TT>state</TT>,
<TT>windSpeed</TT>, <TT>windowHeight</TT>. Boolean variables should be named appropriately:
<TT>windowIconized</TT>, <TT>fileIsOpen</TT>.
</UL>
<CENTER>
<H4><A NAME="Heading37"></A><FONT COLOR="#000077">Spelling and Capitalization of
Names</FONT></H4>
</CENTER>
<P>Spelling and capitalization should not be overlooked when creating your own style.
Some tips for these areas include the following:
<UL>
<LI>Use all uppercase and underscore to separate the logical words of names, such
as <TT>SOURCE_FILE_TEMPLATE</TT>. Note, however, that these are rare in C++. Consider
using constants and templates in most cases.
<P>
<LI>All other identifiers should use mixed case--no underscores. Function names,
methods, class, <TT>typedef</TT>, and <TT>struct</TT> names should begin with a capitalized
letter. Elements such as data members or locals should begin with a lowercase letter.
<P>
<LI>Enumerated constants should begin with a few lowercase letters as an abbreviation
for the <TT>enum</TT>. For example:
</UL>
<PRE><FONT COLOR="#0066FF">enum TextStyle
{
tsPlain,
tsBold,
tsItalic,
tsUnderscore,
};
</FONT></PRE>
<CENTER>
<H4><A NAME="Heading38"></A><FONT COLOR="#000077">Comments</FONT></H4>
</CENTER>
<P>Comments can make it much easier to understand a program. Sometimes you will not
work on a program for several days or even months. In this time you can forget what
certain code does or why it has been included. Problems in understanding code can
also occur when someone else reads your code. Comments that are applied in a consistent,
well thought out style can be well worth the effort. There are several tips to remember
concerning comments:
<UL>
<LI>Wherever possible, use C++ <TT>//</TT> comments rather than the <TT>/* */</TT>
style.
<P>
<LI>Higher-level comments are infinitely more important than process details. Add
value; do not merely restate the code.
</UL>
<PRE><FONT COLOR="#0066FF">n++; // n is incremented by one
</FONT></PRE>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -