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

📄 c++.tex

📁 c++的一些简单但是特别精炼的例子 关于栈和链表
💻 TEX
📖 第 1 页 / 共 5 页
字号:
\documentstyle[12pt,fullpage]{article}\newcommand{\putfig}[3]%{\begin{figure}%\centerline{%\psfig{figure=#1.ps,width=#3}}%\caption{#2}%\label{fig:#1}%\end{figure}}\input{psfig}\begin{document}\begin{figure*}[t]\begin{center}{\LARGE\bf A Quick Introduction to C++}\vspace{3.0ex}{\Large Tom Anderson}\end{center}\end{figure*}\renewcommand{\thefootnote}{\fnsymbol{footnote}}\footnotetext{This article is based on an earlier version written by Wayne Christopher.}\renewcommand{\thefootnote}{}\renewcommand{\thefootnote}{\arabic{footnote}}\begin{quote}``If programming in Pascal is like being put in a straightjacket,then programming in C is like playing with knives, and programmingin C++ is like juggling chainsaws.'' \\ \hbox{} \hfill Anonymous.\end{quote}\section{Introduction}This note introduces some simple C++ concepts and outlines asubset of C++ that is easier to learn and use thanthe full language.  Although we originally wrote this note forexplaining the C++ used in the Nachos project, I believe it is useful to anyone learning C++.I assume that you are already somewhat familiar with C conceptslike procedures, for loops, and pointers; these are pretty easyto pick up from reading Kernighan and Ritchie's ``The C Programming Language.''I should admit up front that I am quite opinionated about C++, ifthat isn't obvious already.I know several C++ purists (an oxymoron perhaps?) who violentlydisagree with some ofthe prescriptions contained here; most of the objections are ofthe form, ``How could you have possibly left out feature X?''However, I've found from teaching C++ to nearly 1000 undergradsover the past several years that the subset of C++ described here ispretty easy to learn, taking only a day or so for most students to get started.The basic premise of this note is that while object-orientedprogramming is a useful way to simplify programs, C++ is a wildlyover-complicatedlanguage, with a host of features that only very, very rarely find alegitimate use.  It's not too far off the mark to say that C++ includesevery programming language feature ever imagined, and more.The natural tendency when faced with a new language featureis to try to use it, but in C++ this approach leads to disaster.Thus, we need to carefully distinguish between (i) those concepts that are fundamental (e.g., classes, member functions, constructors)-- ones that everyone should know and use, (ii) those that are sometimes but rarely useful (e.g., single inheritance, templates) -- ones thatbeginner programmers should be able to recognize (in case they run acrossthem) but avoid using in their own programs, at least for a while,and (iii) those that are just a bad idea and should be avoided likethe plague (e.g., multiple inheritance, exceptions, overloading,references, etc).Of course, all the items in this last category have their proponents,and I will admit that, like the hated goto, it is possible toconstruct cases when the program would be simpler using a goto ormultiple inheritance.  However, it ismy belief that most programmers will never encounter such cases,and even if you do, you will be much more likely to misuse the feature than properly apply it.For example, I seriously doubt an undergraduate would need any of the features listed under (iii) for any course project (at leastat Berkeley this is true).  And if you find yourself wanting to use a feature like multiple inheritance, then, my advice is to fully implement your program both with and without the feature, and choose whichever is simpler.  Sure, this takes more effort, butpretty soon you'll know from experience when a feature is useful and whenit isn't, and you'll be able to skip the dual implementation.A really good way to learn a language is to read clear programs in thatlanguage.  I have tried to make the Nachos code as readable as possible;it is written in the subset of C++ described in this note.It is a good idea to look over the first assignment as you read thisintroduction.  Of course, your TA's will answer any questions you mayhave.You should not need a book on C++ to do the Nachos assignments, but if you are curious, there is a large selection of C++ booksat Cody's and other technical bookstores. (My wife quips that C++ wasinvented to make researchers at Bell Labs rich from writing``How to Program in C++'' books.)   Most new software developmentthese days is being done in C++, so it is a pretty good bet you'll run across it in the future.  I use Stroustrup's "The C++Programming Language" as a reference manual, although other books may be more readable.  I would also recommend Scott Meyer's``Effective C++'' for people just beginning to learn the language,and Coplien's ``Advanced C++'' once you've been programming in C++ for a couple years and are familiar with the language basics.Also, C++ is continually evolving, so be careful to buy books that describethe latest version (currently 3.0, I think!).\section{C in C++}To a large extent, C++ is a superset of C, and most carefully writtenANSI C will compile as C++.  There are a few major caveats though:\begin{enumerate}\item All functions must be declared before they are used, rather thandefaulting to type {\tt int}.\item All function declarations and definition headers must usenew-style declarations, e.g.,\begin{verbatim}extern int foo(int a, char* b);\end{verbatim}The form {\tt extern int foo();} means that {\tt foo} takes {\it no}arguments, rather than arguments of an unspecified type and number.In fact, some advise using a C++ compiler evenon normal C code, because it will catch errors like misused functions thata normal C compiler will let slide.\item If you need to link C object files together with C++, when youdeclare the C functions for the C++ files, they must be done like this:\begin{verbatim}extern "C" int foo(int a, char* b);\end{verbatim}Otherwise the C++ compiler will alter the name in a strange manner.\item There are a number of new keywords, which you may not use asidentifiers --- some common ones are {\tt new}, {\tt delete}, {\ttconst}, and {\tt class}.\end{enumerate}\section{Basic Concepts}Before giving examples of C++ features, I will first go over some ofthe basic concepts of object-oriented languages.  If this discussionat first seems a bit obscure, it will become clearer when we getto some examples.\begin{enumerate}\item {\bf Classes and objects}.  A class is similar to a C {\em structure},except that the definition of the data structure, {\em and} all of the functions that operate on the data structure are grouped togetherin one place.  An {\em object} is an instance of a class (an instanceof the data structure); objects share the same functions with other objectsof the same class, but each object (each instance) has its own copy of the data structure.  A class thus defines two aspects of the objects: the {\em data} they contain, and the {\em behavior} they have.\item {\bf Member functions}.  These are functions which areconsidered part of the object and are declared in the classdefinition.  They are often referred to as {\em methods} of the class.In addition to member functions, a class's behavior is also definedby:\begin{enumerate}\item What to do when you create a new object (the {\bf constructor}for that object) -- in other words, initialize the object's data.\item What to do when you delete an object (the {\bf destructor} forthat object).\end{enumerate}\item {\bf Private vs. public members}.  A public member of a class isone that can be read or written by anybody, in the case of a datamember, or called by anybody, in the case of a member function.  Aprivate member can only be read, written, or called by a memberfunction of that class.\end{enumerate}Classes are used for two main reasons: (1) it makes it much easier toorganize your programs if you can group together data with thefunctions that manipulate that data, and (2) the use of privatemembers makes it possible to do {\em information hiding}, so that youcan be more confident about the way information flows in yourprograms.\subsection{Classes}C++ classes are similar to C structures in many ways.  In fact, a C++struct is really a class that has only public data members.In the following explanation of how classes work, we will use a stackclass as an example.\begin{enumerate}\item {\bf Member functions.}   Here is a (partial) example of a classwith a member function and some data members:\begin{verbatim}class Stack {  public:    void Push(int value); // Push an integer, checking for overflow.    int top;          // Index of the top of the stack.    int stack[10];    // The elements of the stack.};voidStack::Push(int value) {    ASSERT(top < 10);		// stack should never overflow    stack[top++] = value;}\end{verbatim}This class has two data members, {\tt top} and {\tt stack}, and onemember function, {\tt Push}.  The notation {\em class}::{\em function} denotes the{\em function} member of the class {\em class}.  (In the style we use,most function names are capitalized.)  The function is defined beneathit.  As an aside, note that we use a call to {\tt ASSERT} to check that the stack hasn't overflowed; ASSERT drops into the debugger if the conditionis false.  It is an extremely good idea for you to use ASSERTstatements liberally throughout your code to document assumptionsmade by your implementation.  Better to catch errors automaticallyvia ASSERTs than to let them go by and have your program overwrite random locations.  In actual usage, the definition of {\tt class Stack} would typicallygo in the file {\tt stack.h} and the definitions of the memberfunctions, like {\tt Stack::Push}, would go in the file {\ttstack.cc}.If we have a pointer to a {\tt Stack} object called {\tt s}, we canaccess the {\tt top} element as {\tt s->top}, just as in C.  However,in C++ we can also call the member function using the following syntax:\begin{verbatim}    s->Push(17);\end{verbatim}Of course, as in C, {\tt s} must point to a valid {\tt Stack} object.Inside a member function, one may refer to the members of the classby their names alone.  In other words, the class definitioncreates a scope that includes the member (function and data) definitions.Note that if you are inside a member function, you can get a pointerto the object you were called on by using the variable {\tt this}.If you want to call another member function on the same object, youdo not need to use the {\tt this} pointer, however.  Let's extend the Stackexample to illustrate this by adding a {\tt Full()} function.\begin{verbatim}class Stack {  public:    void Push(int value); // Push an integer, checking for overflow.    bool Full();       // Returns TRUE if the stack is full, FALSE otherwise.    int top;          // Index of the lowest unused position.    int stack[10];    // A pointer to an array that holds the contents.};\end{verbatim}\newpage\begin{verbatim}boolStack::Full() {    return (top == 10);}\end{verbatim}Now we can rewrite {\tt Push} this way:\begin{verbatim}voidStack::Push(int value) {    ASSERT(!Full());    stack[top++] = value;}\end{verbatim}We could have also written the ASSERT:\begin{verbatim}    ASSERT(!(this->Full());\end{verbatim}but in a member function, the \verb+this->+ is implicit.The purpose of member functions is to encapsulate the functionality ofa type of object along with the data that the object contains.  Amember function does not take up space in an object of the class.\item {\bf Private members.}  One can declare somemembers of a class to be {\it private}, which are hidden to all butthe member functions of that class, and some to be {\it public}, whichare visible and accessible to everybody.  Both data and function memberscan be either public or private.In our stack example, note that once we have the {\tt Full()}

⌨️ 快捷键说明

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