(Translation: The translation of this article is quite hard. Bjarne Stroustrup is worth opening a generation of C language, not only thinking deeply, but also in the words of the words, there are many places, the translator repeatedly considers, can not achieve the ideal effect Only do you have to do our best. TextML format documentation See the Character: http://www.wushuang.net If you have any comments and suggestions for this translation, please send a letter to the translation: onekey@163.com. The address of the original text is: http://www.research.att.com/~bs/bs_faq2.html) (Dr. Bjarne Stroustrup) (Born in Denmark in 1950, graduated from the University of Arus, United Kingdom, AT & T Large-scale program design research department, AT & T Bell Lab and ACM Member. In 1979, b. S began to develop a language. At that time, it was called "c with class", and later evolved as C . 1998, ANSI / ISO C The standard is established, the same year, b. S The third edition of the C Programming Language is launched.) This is some people who often ask questions about C style and techniques. If you can make a better problem, or ask for these answers, please send me email (BS@research.att.com). Keep in mind that I can't spend all the time to update my homepage. See my General FAQ for more questions. For terms and concepts, see My C Glossary (C Glossary.). Please note that this is just a list of common problems and answers. It cannot replace a well-selected example and explanation in an excellent textbook. It also provides detailed and accurate descriptions like a reference manual or language standard. For questions about C , see "The Design and Evolution Of C ). For the use of the C language and the standard library, see "C Programming Language" (THE C Programming Language).
Directory: How do I write this very simple program? Why do you have to spend so long? Why is an empty class not of 0? Do I have to give data on the class declaration? Why is the member function not to virtual? Why is the destructor not Virtual by default? Why can't you have a virtual constructor? Why is overloaded in inheritance? Can I call a virtual function in the constructor? Is there a "Delete" (Placement DELETE)? Can I prevent someone from inheriting my own class? Why can't I define constrays for template parameters? Since there is already an excellent QSort () function, why still need a sort ()? What is a function object (Function Object)? How should I deal with memory leak? Why can't I continue after capturing an exception? Why is there a function equivalent to a realloc () in C ? How to use an exception? How to read a string from the input? Why does C does not provide "Finally" construct? What is an automatic pointer (Auto_PTR), why don't you automatically array (Auto_Array)? Can I mix use C-style and C style memory distribution and redistribution? Why do I have to use a shape to convert * void? How do I write this very simple program? Especially in the beginning of a semester, I often receive many asks about writing a very simple program. The most typical solution of this problem is to read it repeatedly, do something, and write the answer. Here is an example of this: #include Remember to add the source file with the .cpp suffix, otherwise the compiler may think that it is a C code rather than C . Yes, the main () function returns an INT value. To read a standard vector (Vector), you can avoid overflow errors in the buffer of the size. Read in an array, do not produce "simple error", which has exceeded a novice capability - if you did it, then you are not a novice. If you expressed this, I suggest you read my article "Learn Standard C as a new language" ("Learning Standard C As a New Language), you can list your book (My Publications List) Download it in it. Cin.eof () is a check in convection format. In fact, it checks whether the loop is ended in finding an end-of-file (if not, then means that the input is not in the given format). For more description, see Section of the "Stream State" in your C textbook. Vector knows its own size, so I don't need to calculate the number of elements. This program does not contain explicit memory management. Vector maintains a stack in a memory to store its elements. When a vector requires more memory, it assigns some; it will release memory when it no longer survives. Thus, the user does not need to care about the memory allocation and release of elements in Vector. The program ends when encountering an "end-file". If you run it under the UNIX platform, "end-file" is equal to Ctrl D on the keyboard. If you are in the Windows platform, you may tend to use this slightly more complex version by using a bug, you can use the word "end" to indicate that the input has ended. #include Look at this typical object-oriented program example: Class Shape {public: // Interface to users of shapes virtual void draw () const; virtual void rotate (int de devid); // ... protected: // Common data For import center; color color; {}; // ... protected: int RADIUS; // ... protected: int RADIUS; / / ... protected: int RADIUS; / / ... PROTECTED: INT RADIUS; // / ...}; Class Triangle: PUBLIC Shape {public: void draw () const; void rotate (int); // ... protected: Point A, B, C; // ...}; design idea is The user manipulates them through the PUBLIC interface of Shape, while the implementation of the derived class (such as a Circle and Triangle) shares the part of the PROTECTED member. This is not an easy thing: determine which implementation part is useful for all derived classes and shares it. Therefore, Protected members often do much more changes than the public interface. For example, although the theoretical "center" is a valid concept for all graphics, it is a very troublesome thing when you want to maintain a triangular "center" - for triangles, When it is only when it is really needed, it makes sense. Protected members are likely to rely on the details of the implementation, while Shape's users (translation: User is translated into users, referring to the code, the same as the shape class, the same), but not necessarily rely on them. For example, many (most?) Use Shape's code to logically unrelated to "color", but due to the existence of "color" in Shape, it may require a bunch of complex header files to combine operations The color concept of the system. When the Protected section changes, the code to use Shape must be recompiled - even if only the implementation of the derived class can access the protected member. Thus, "INFORTION Helpful to Implement" in the base class becomes as sensitive to the user, and its existence leads to unstable and unstable compilation of user code. (When the implementation is changed), and the header file is not controlled in the user code (because "" implementation related information "needs them). Sometimes this is called "BRITTLE BASE CLASS Problem). A very obvious solution is to ignore "implementation-related information" as those in the base class. In other words, use the interface, pure interface. That is to say, use the abstract base class to indicate the interface: Class Shape {public: // Interface to users of shapes virtual void Draw () const = 0; Virtual Void Rotate (int devot) = 0; Virtual Point Center () Const = 0; // ... // NO DATA}; Class Circle: Public Shape {public: Void Draw () const; void Draw (int) {} point center () const {return center;} // .. COLOR COL; INT RADIUS; // ...}; class triangle: public shape {public: void draw () const; void rotate (int); point center () const; // ... Protected: Color Color Color Color COL; Point A, B, C; // ...}; Now, the relationship between the change in the implementation part of the user code and the derivative class is isolated. I have seen this technology to reduce the time of compilation. However, what if there is indeed public information useful for all derived classes (or only some derived classes)? You can simply package these information into a class, then derived a class from it: Class Shape {public: // interface to users of shapes virtual void draw () const = 0; Virtual Void Rotate (int De De De De De De De De De De De De De De De De De De De De De De De De De De Virtual point center () const = 0; // ... // no data}; struct common {color color color color: // ...}; Class Circle: Public Shape, protected common {public: void draw () const; Void Rotate (int) {} point center () const {return center;} // ... protected: point; int RADIUS;}; class triangle: public shape, protected common {public: void draw () const; void Rotate (int); point center () const; // ... protected: Point A, B, C;}; Why is an empty class size not 0? To be clear, the address of the two different objects is also different. Based on the same reason, NEW always returns a pointer to different objects. Take a look: Class Empty {}; void f () {EMPTY A, B; if (& a == & b) cout << "Impossible: Report Error to Compiler Suppirl"; EMPTY * P1 = New Empty; EMPTY * P2 = New Empty; if (p1 == p2) cout << "Impossible: Report Error to Compiler Suppilier";} There is an interesting rule: an empty base class does not necessarily have a separate byte. Struct x: Empty {Int a; // ...}; void f (x * p) {void * p1 = p; void * p2 = & p-> a; if (p1 == p2) cout << "Nice : Good Optimizer ";} This optimization is allowed, which can be widely used. It allows programmers to use empty classes to express some simple concepts. Some compilers are now available for this "empty base class optimization). Do I have to give data on the class declaration? no need. If an interface does not require data, it is not necessary to give data in a class as an interface definition. In order to give them in the derived class. See "Why do you have to spend so long?". Sometimes you must give data in a class. Consider the case of Class Complex: Template Only class is in behavior is its derived interface (these derived classes are often distributed in the heap, accessible through pointers or quotes), and virtual functions make sense. So when you should define the destructor as a virtual? When the class has at least one virtual function. Having virtual functions means a class is a derived interface, in which case a derived class may be destroyed by a base class pointer. For example: class base {// ... virtual ~ base ();}; class deive: public base {// ... ~ derived ();}; void f () {base * p = new derived; delete P ; // Virtual destructor guaranteed ~ Derived function is called} If the analyte function of the base class is not a virtual, the sect of the sect of the class will not be called - this may produce a bad result, such as derived class Resources will not be released. Why can't you have a virtual constructor? Virtual call is a mechanism that works in the case where a given information is incomplete (given partial information). In particular, virtual allows us to call a function, for this function, only know its interface, and do not know the specific object type. But to create an object, you have to have full information. In particular, you need to know the specific type of object to be established. Therefore, the call to the constructor cannot be virtual. When an object is required, an indirect technology is often used as a "virtual constructor". For example, see the "C Programming Language" third edition 15.6.2. The following example shows a mechanism: how to use an abstract class to create an appropriate type of object. Struct f {// Object set function interface Virtual a * make_an_a () const = 0; Virtual B * Make_a_b () const = 0;}; Void User (const f & fac) {a * p = fac.make_an_a (); // As a suitable type B * q = fac.make_a_b (); // uses B as the appropriate type // ...} struct fx: f {a * make_an_a () const {return new AX (); } // AX is a derived b * Make_a_b () const {return new bx ();} // ax is a derived}; struct fy: f {a * make_an_a () const {return new aY ();} // AY is a derived b * Make_a_b () const {return new by ();} // BY is a derived}; int main () {user (fx ()); // This user establishes AX and BX User (fy ()); // This user establishes AY and BY / / ...} This is a deformerus of the "factory mode". The key is that the user of the user function is completely separated from the information of the class of AX or AY. Why is overloaded in inheritance? This problem (very common) often appears in such an example: #include Take a look at this: #include In the C type system, there is nothing to make us confirmed that P1 must point to an object that is dispatched by the ARENA type A1. P1 may point to any place to anything dispatched. However, sometimes the programmer is known, so this is a way: Template Take a look at this: Template So, in the C language, is there anything similar to can_copy - or better -? In "C language design and evolution", there is a problem in achieving this universal constraint in C . Since then, there have been many ways to make the constraint class more easily, while still triggering good error messages. For example, I trust the way I use the function pointer used in Can_copy, it originates from Alex Stepanov and Jeremy Siek. I don't think that can_copy () is already standardized - it requires more use. Similarly, in the C community, a variety of different constraints are used; which constraint template is most effective in extensive use, and has not reached an agreement. However, this way is very common, which is more common than the mechanism for constraint inspections provided by the language. In any case, when we write a template, we have the most abundant expression of C .