📄 ch21.htm
字号:
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 ofNames</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 notwork on a program for several days or even months. In this time you can forget whatcertain code does or why it has been included. Problems in understanding code canalso 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 rememberconcerning 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><UL> <LI>This comment isn't worth the time it takes to type it in. Concentrate on the semantics of functions and blocks of code. Say what a function does. Indicate side effects, types of parameters, and return values. Describe all assumptions that are made (or not made), such as "<TT>assumes </TT>n<TT> is non-negative</TT>" or "<TT>will return -1 if </TT>x<TT> is invalid</TT>". Within complex logic, use comments to indicate the conditions that exist at that point in the code. <P> <LI>Use complete English sentences with appropriate punctuation and capitalization. The extra typing is worth it. Don't be overly cryptic and don't abbreviate. What seems exceedingly clear to you as you write code will be amazingly obtuse in a few months. <P> <LI>Use blank lines freely to help the reader understand what is going on. Separate statements into logical groups.</UL><CENTER><H4><A NAME="Heading39"></A><FONT COLOR="#000077">Access</FONT></H4></CENTER><P>The way you access portions of your program should also be consistent. Some tipsfor access include these:<UL> <LI>Always use <TT>public:</TT>, <TT>private:</TT>, and <TT>protected:</TT> labels; don't rely on the defaults. <P> <LI>List the public members first, then protected, then private. List the data members in a group after the methods. <P> <LI>Put the constructor(s) first in the appropriate section, followed by the destructor. List overloaded methods with the same name adjacent to each other. Group accessor functions together when possible. <P> <LI>Consider alphabetizing the method names within each group and alphabetizing the member variables. Be sure to alphabetize the filenames in <TT>include</TT> statements. <P> <LI>Even though the use of the <TT>virtual</TT> keyword is optional when overriding, use it anyway; it helps to remind you that it is virtual, and also keeps the declaration consistent.</UL><CENTER><H4><A NAME="Heading40"></A><FONT COLOR="#000077">Class Definitions</FONT></H4></CENTER><P>Try to keep the definitions of methods in the same order as the declarations.It makes things easier to find.</P><P>When defining a function, place the return type and all other modifiers on a previousline so that the class name and function name begin on the left margin. This makesit much easier to find functions.<CENTER><H4><A NAME="Heading41"></A><FONT COLOR="#000077">include Files</FONT></H4></CENTER><P>Try as hard as you can to keep from including files into header files. The idealminimum is the header file for the class this one derives from. Other mandatory <TT>include</TT>swill be those for objects that are members of the class being declared. Classes thatare merely pointed to or referenced only need forward references of the form.</P><P>Don't leave out an <TT>include</TT> file in a header just because you assume thatwhatever CPP file includes this one will also have the needed <TT>include</TT>.<BLOCKQUOTE> <P><HR><FONT COLOR="#000077"><B>TIP:</B></FONT><B> </B>All header files should use inclusion guards. <HR></BLOCKQUOTE><CENTER><H4><A NAME="Heading42"></A><FONT COLOR="#000077">assert()</FONT></H4></CENTER><P>Use <TT>assert()</TT> freely. It helps find errors, but it also greatly helpsa reader by making it clear what the assumptions are. It also helps to focus thewriter's thoughts around what is valid and what isn't.<CENTER><H4><A NAME="Heading43"></A><FONT COLOR="#000077">const</FONT></H4></CENTER><P>Use <TT>const</TT> wherever appropriate: for parameters, variables, and methods.Often there is a need for both a <TT>const</TT> and a non-<TT>const</TT> versionof a method; don't use this as an excuse to leave one out. Be very careful when explicitlycasting from <TT>const</TT> to non-<TT>const</TT> and vice versa (there are timeswhen this is the only way to do something), but be certain that it makes sense, andinclude a comment.<CENTER><H3><A NAME="Heading44"></A><FONT COLOR="#000077">Next Steps</FONT></H3></CENTER><P>You've spent three long, hard weeks working at C++, and you are now a competentC++ programmer, but you are by no means finished. There is much more to learn andmany more places you can get valuable information as you move from novice C++ programmerto expert.</P><P>The following sections recommend a number of specific sources of information,and these recommendations reflect only my personal experience and opinions. Thereare dozens of books on each of these topics, however, so be sure to get other opinionsbefore purchasing.<CENTER><H4><A NAME="Heading45"></A><FONT COLOR="#000077">Where to Get Help and Advice</FONT></H4></CENTER><P>The very first thing you will want to do as a C++ programmer will be to tap intoone or another C++ conference on an online service. These groups supply immediatecontact with hundreds or thousands of C++ programmers who can answer your questions,offer advice, and provide a sounding board for your ideas.</P><P>I participate in the C++ Internet newsgroups (<TT>comp.lang.c++ </TT>and<TT> comp.lang.c++.moderated</TT>),and I recommend them as excellent sources of information and support.</P><P>Also, you may want to look for local user groups. Many cities have C++ interestgroups where you can meet other programmers and exchange ideas.<CENTER><H4><A NAME="Heading46"></A><FONT COLOR="#000077">Required Reading</FONT></H4></CENTER><P>The very next book I'd run out and buy and read is</P><P>Meyers, Scott. Effective C++ (ISBN: 0-201-56364-9). Addison-Wesley Publishing,1993.</P><P>This is by far the most useful book I've ever read, and I've read it three times.<CENTER><H4><A NAME="Heading47"></A><FONT COLOR="#000077">Magazines</FONT></H4></CENTER><P>There is one more thing you can do to strengthen your skills: subscribe to a goodmagazine on C++ programming. The absolute best magazine of this kind, I believe,is C++ Report from SIGS Publications. Every issue is packed with useful articles.Save them; what you don't care about today will become critically important tomorrow.</P><P>You can reach C++ Report at SIGS Publications, P.O. Box 2031, Langhorne, PA 19047-9700.I have no affiliation with the magazine (I work for two other publishers!), but theirmagazine is the best, bar none.<CENTER><H4><A NAME="Heading48"></A><FONT COLOR="#000077">Staying in Touch</FONT></H4></CENTER><P>If you have comments, suggestions, or ideas about this book or other books, I'dlove to hear them. Please write to me at <TT>jliberty@libertyassociates.com</TT>,or check out my Web site: <TT>www.libertyassociates.com</TT>. I look forward to hearingfrom you.<BLOCKQUOTE> <P><HR><B>DO</B> look at other books. There's plenty to learn and no single book can teach you everything you need to know. <B>DON'T</B> just read code! The best way to learn C++ is to write C++ programs. <B>DO </B>subscribe to a good C++ magazine and join a good C++ user group. <HR></BLOCKQUOTE><CENTER><H3><A NAME="Heading49"></A><FONT COLOR="#000077">Summary</FONT></H3></CENTER><P>Today you saw how some of the standard libraries shipped with your C++ compilercan be used to manage some routine tasks. <TT>Strcpy()</TT>, <TT>strlen()</TT>, andrelated functions can be used to manipulate null-terminated strings. Although thesewon't work with the string classes you create, you may find that they provide functionalityessential to implementing your own classes.</P><P>The time and date functions allow you to obtain and manipulate time structures.These can be used to provide access to the system time for your programs, or theycan be used to manipulate time and date objects you create.</P><P>You also learned how to set and test individual bits, and how to allocate a limitednumber of bits to class members.</P><P>Finally, C++ style issues were addressed, and resources were provided for furtherstudy.<CENTER><H3><A NAME="Heading50"></A><FONT COLOR="#000077"><B>Q&A</B></FONT></H3></CENTER><DL> <DD><B>Q. Why are the standard libraries included with C++ compilers, and when would you use them?</B><BR> <BR> <B>A. </B>They are included for backwards-compatibility with C. They are not type-safe, and they don't work well with user-created classes, so their use is limited. Over time, you might expect all of their functionality to be migrated into C++ specific libraries, at which time the standard C libraries would become obsolete.<BR> <BR> <B>Q. When would you use bit structures rather than simply using integers?<BR> </B><BR> <B>A.</B> When the size of the object is crucial. If you are working with limited memory or with communications software, you may find that the savings offered by these structures is essential to the success of your product.<BR> <BR> <B>Q. Why do style wars generate so much emotion?<BR> </B><BR> <B>A.</B> Programmers become very attached to their habits. If you are used to this indentation,</DL><PRE><FONT COLOR="#0066FF">if (SomeCondition){ // statements} // closing brace</FONT></PRE><DL> <DD>it is a difficult transition to give it up. New styles look wrong and create confusion. If you get bored, try logging onto a popular online service and asking which indentation style works best, which editor is best for C++, or which product is the best word processor. Then sit back and watch as ten thousand messages are generated, all contradicting one another.<BR> <BR> <B>Q. What is the very next thing to read?<BR> </B><BR> <B>A.</B> Tough question. If you want to review the fundamentals, read one of the other primers. If you want to hone C++, run out and get Scott Meyers' Effective C++. Finally, if you want to write for Windows or the Mac, it might make sense to pick up a primer on the <BR> platform.<BR> <BR> <B>Q. Is that it?<BR> </B><BR> <B>A.</B> Yes! You've learned C++, but...no. Ten years ago it was possible for one person to learn all there was to know about microcomputers, or at least to feel pretty confident that he was close. Today it is out of the question: You can't possibly catch up, and even as you try the industry is changing. Be sure to keep reading, and stay in touch with the resources that will keep you up with the latest changes: magazines and online services.</DL><CENTER><H4><A NAME="Heading51"></A><FONT COLOR="#000077">Quiz</FONT></H4></CENTER><DL> <DD><B>1.</B> What is the difference between <TT>strcpy()</TT> and <TT>strncpy()</TT>?<BR> <BR> <B>2.</B> What does <TT>ctime()</TT> do?<BR> <BR> <B>3.</B> What is the function to call to turn an ASCII string into a <TT>long</TT>?<BR> <BR> <B>4.</B> What does the complement operator do?<BR> <BR> <B>5.</B> What is the difference between <TT>OR</TT> and exclusive <TT>OR</TT>?<BR> <BR> <B>6.</B> What is the difference between <TT>&</TT> and <TT>&&</TT>?<BR> <BR> <B>7.</B> What is the difference between <TT>|</TT> and <TT>||</TT>?</DL><CENTER><H4><A NAME="Heading52"></A><FONT COLOR="#000077">Exercises</FONT></H4></CENTER><DL> <DD><B>1.</B> Write a program to safely copy the contents of a 20-byte string to a 10-byte string, truncating whatever won't fit.<BR> <BR> <B>2.</B> Write a program that tells the current date in the form 7/28/94.<BR> <BR> <B>3.</B> Write a program that creates 26 flags (labeled a-z). Prompt the user to enter a sentence, and then quickly report on which letters were used by setting and then reading the flags.<BR> <B><BR> 4.</B> Write a program that adds two numbers without using the addition operator (<TT>+</TT>). Hint: use the bit operators! <CENTER> <DD><BR> <BR> <A HREF="ch20.htm"><IMG SRC="../buttons/BLANPREV.GIF" WIDTH="37" HEIGHT="37" ALIGN="BOTTOM" BORDER="0"></A><A HREF="http://www.mcp.com/sams"><IMG SRC="../buttons/BLANHOME.GIF" WIDTH="37" HEIGHT="37" ALIGN="BOTTOM" BORDER="0"></A><A HREF="../index.htm"><IMG SRC="../buttons/BLANTOC.GIF" WIDTH="37" HEIGHT="37" ALIGN="BOTTOM" BORDER="0"></A><A HREF="ch21rv3.htm"><IMG SRC="../buttons/BLANNEXT.GIF" WIDTH="37" HEIGHT="37" ALIGN="BOTTOM" BORDER="0"></A><A HREF="#heading1"><IMG SRC="../buttons/BLANTOP.GIF" WIDTH="37" HEIGHT="37" ALIGN="BOTTOM" BORDER="0"></A></CENTER></DL></BODY></HTML>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -