C ++ language FAQ solution: # 105 ~ # 120

xiaoxiao2021-03-06  31

This is the traditional translation of "C frequently asked Questions" found from Taiwan http://www.cis.nctu.edu.tw/chinese/doc/research/, found "C Frequently Asked Questions" Ye Bingzhe, is also a translator of "C Programming Language" 3 / e, this article is very good, paying it for learning purposes, I didn't get the author's authorization, the copyright of the original article still belongs to the original author .c FAQ == PART 4/4 ===================================== Comp.Lang.c Frequently Asked Questions List (with Answers , Fortunately). copyright (c) 1991-96 Marshall P. Cline, ph.d.posting 4 of 4.posting # 1 Explains Copying Permissions, (NO) WARRANTY, TABLE-OF-Contents, etc ====== ================================== ■ Section 17: and C link / and C relationship === ============================================= q105: How to call C from C "F (int , char, float? Tell the C compiler that: it is a function of C: EXTERN "C" void f (int, char, float); determine if you have an incapacity coming in a full function prototype (Function Prototype).

The function of a bracket can be framed by braces, as follows: Extern "C" {void * malloc (size_t); char * STRCPY (Char * DEST, Const Char * src); int printf (const char * fmt, .. .);} ======================================== q106: How can I build one C functions "F (int, char, float), can also be called C call? Want to let the C compiler know "F (int, char, float" will be used by the C compiler, and to use the "Extern C" syntax that the previous FAQ has detailed in detail. The function is then defined within the C module: Void F (int X, char y, float z) {// ...} "Extern C" tells the compiler: send to external information to Linker to use C's call convention And signature encoding method (for example, a front line). Since C does not have a multi-load ability, you can't let the C program get a multi-load function group at the same time. Warnings and practical matters: * Your "main ()" should be compiled with C (for the initialization of static objects). * Your C compiler should set up the program (for some special link libraries). * Your C and C compilers may be the same brand, and are compatible versions (ie: have the same call conventions, etc.). ================================================= q107: Why is Linker has this error message: Is the C / C function calls by the C / C function? See the first two FAQs for the use of Extern "C".

======================================== q108: How to pass the C category object Give / pass the function of C? Example: / ****** C / C Header file: fred.h ****** / # ifdef __cplusplus / * "__ cplusplus" is #defined if / only-ifcompiler IS C * / extern "C" { # endif # ifdef __STDC__extern void c_fn (struct Fred *); / * ANSI-C prototypes * / extern struct Fred * cplusplus_callback_fn (struct Fred *); # elseextern void c_fn (); / * K & R style * / extern struct Fred * cplusplus_callback_fn (); # ENDIF # ifdef __cplusplus} # Endif # ifdef __cplusplusclass fred {public: fred (); void wilma (int); private: int A _;}; # Endif "Fred.c" is a C module: #include "fred .h "fred :: fred (): a_ (0) {} void Fred :: Wilma (INT A): A_ (a) {} fred * cplusplus_callback_fn (fred * fred) {fred-> Wilma (123); Return Fred;} "main.c" is a C module: #include "fred.h" int main () {fred fred; c_fn (& fre);} "c-fn.c" is a C Module: #include " Fred.h "void c_fn (struct fred * fred) {CPLUSPLUS_CALLBACK_FN (FRED);} Points to the pointer to the C object to the function of the C , if the pointer to the recovery is not" exactly the same ", failure. For example, do not pass a pointer to a substrate category, it recovers a derivative category, because the C compiler does not understand how to transform multiple and virtual inheritance pointers. ================================================= q109: c function can not access C Category object information? Sometimes it can. (Please read the previous reading of the FAQ that passes the C object between the C function.

You can safely access the C object information from the C function, as long as C object category: * No virtual function (including inherited virtual functions). * All information is in the same access level (private / protected) /public ).* There is no virtual function in a sub-object that is fully included. If the C category has any substrate category (or if there is a base category in a fully included sub-object), it is technically to access the information. There is no portability because the language is not specified in the category configuration under the inheritance. However, all C compilers are the same: the base category object appears first (under multiple inheritance, it is arranged by left to right), sub-objects. Also, if the category (or any substrate category) contains any virtual functions, you can often (but not always) assume that there is a "void *" that appears in the object's first virtual function, or in this object The first word there. Similarly, language is not specified, but this seems to be the practice taken by "everyone". If this category has any virtual base categories, the situation will be more complex and there is no portability. Common practice is to let the object contain the object (V) of the base category (regardless of "V" appears in the inheritance layer), other parts of the object appears in a normal order. Each derived category of this virtual base category is actually a "pointer" pointing to some of the last object of V. ================================================= q110: Why do I always think that C let me " Far away from the machine, isn't it like C? Because in fact, it is exactly. As an OOPL, C lets you think in the field of this issue, let you design the language in the language of the problem, not the field of solving the problem. The strongest place is: it does not have a "hidden mechanism": What you see is what you get, you can read the C's program, while "see" each systematic clock. C is not; C's old hand (like the previous we) often have contradictory psychology (or say "hostility"), but soon they will find: C provides an abstract level and economic performance Ability, greatly reduces maintenance costs, and does not damage and perform efficiency. Naturally, it will write bad programs in any language; C does not ensure any high quality, reusability, abstraction, or any "positive word marker" quality factor. C will not let the quadrographer can't write a problem; she just assists a wise development person to make a high-level software.

=================================== ■ □ Section 18: Pointer to member functions ==== ========================================== q111: "Pointer to the Member Function" and "pointer to the function" Is there a difference in state? Yes it is. Consider the function: int F (char a, float b); if it is a normal function, its type is: int (*) (char, float); if it is a Fred category operation behavior, its type The state is: int (fred :: *) (char, float); ================================== ====== Q112: How to pass pointers that point to member functions to Signal Handler, X Event Callback, etc. [Translation] This is related to UNIX, X Window System, but other systems can also be built. Do not do this. Because if there is no object to activate it, the member function is meaningless, you can't use it directly (if the X window system is written with C , perhaps you can directly pass the reference value of the object, and not only the pointing function Pointer; naturally, the object will contain all functions to be used, even more). If you want to modify the existing software, take the top (non-member) function as a layer of packaging (Wrapper), packet it through other techniques (perhaps in the whole domain variable). This top-level function uses the whole domain variable through the appropriate member function.

For example, if you want to call Fred :: Memfn () in the interrupt: Class Fred {public: void memfn (); static void staticMemfn (); // Using a Static member function //... }/ / wrapper function will remember which object global deactivation member function object: Fred * object_which_will_handle_signal; void Fred_memfn_wrapper () {object_which_will_handle_signal-> memfn ();} main () {/ * signal (SIGINT, Fred :: memfn); * / / / Do not do Signal (SIGINT, FRED_MEMFN_WRAPPER); // OK Signal (SIGINT, FRED :: StaticMemfn); // Also OK} Note: Static member functions do not need real objects to activate, so point to static member functions Pointer, pointers with ordinary pointing functions, have compatible types (see ARM ["Annotated ReferenceManual"] P.25, 158). =============================================================== q113: When I want to be a member function When the Interrupt Services Routine (ISR), why is the compiler generate (type unrequited) error? This is the first two questions, so please take a look at the first two answers. Non-static member functions have a hidden parameters, corresponding to 'this' pointer, the' this' pointer pointing to the case of the object (INSTANCE DATA), but the hardware / firmware of the system interrupt does not provide this' This' parameter. You have to use the "normal" function (not a member of a class) or a static member function to do as an interrupt service routine. A viable solution is: use a static member as an interrupt service routine to let it go to some place to find the case / member's pairing for interrupt calls. In this way, when the interrupt is generated, normal Method will be activated, but in a technical point of view, you have to call a mediation function first. ========================================================== q114: Why can't I get a C function? address? This can be presented by the previous FAQ. Detailed answer: In C , the member function has an implicit parameter, pointing to the object itself ("this" pointer within the member function). Normal C functions and call conventions of member functions can be considered different, so their pointer (pointing to member functions vs pointing function) is not compatible.

C introduces a new pointer: pointing to the member's pointer, to provide an object to activate (see ARM ["AnnotatedReference Manual"] 5.5). Note: Do not force the pointer to the member function into a pointer to the function; this result is undefined, and the lower field may be very miserable. For example, pointing to a pointer to the member function, "Does not ignore" will contain a machine address of a normal function (see ARM, 8.1.2C, P.158). As mentioned before, if you have a pointer to the normal C function, use the upper (non-member) function, or with the "Static" member function (category member function). ======================================================================== how to declare array arrays ? Use "typedef" to keep your brain awake.

Class Fred {public: int F (char X, float y); int G (char X, float y); int i (char x, float y); // ... }; typedef int (fred :: * fredptr) (this is a pointer array pointing to member functions: Here's the array of pointers to Member functions: Fredptr A [4] = {& fred :: f, & fred :: g, & fred :: h, & fred :: i}; call object "fred" a member function: void usercode (fred & fred, int methodnum, char x, float y) {// hypothesis "MethodNum" in [ 0, 3] Interval (Fred. * A [MethodNum]) (x, y);} You can use #define to make this call clearly: #define callmethod (Object, ptrtomethod) ((Object). * (PTRTomethod) CallMethod (FRED, A [MethodNum]) (x, y); ================================== == ■ □ Section 19: Container category with template ============================================ q116: How to insert / Access / change the element from a link serial / mixture table, etc. I will take the simplest "insertion link" as an example. It is easy to put the elements into the serial tail, but it is limited to these features, which will make the link library too low (too low linked library than even worse). A complete solution will make C novice indigestion, so I only mention several projects. The first is the simplest, second and third are preferred. [1] Add a "list" to the nature of "present", add like Advance (), Backup (), Atend (), Atbegin (), GetCurrelem (), SetCurrelem (Elem), Insertelem (ELEM), Removelelec () Wait for operation behavior. Even in this small example is already enough, "there is only one" mark of the current position, I want to access the elements of the two or more positions in the serial (such as: "For all X, Y preface, Do things under the bottom ... "). [2] Take the above List operation behavior and move to a separate category "listPosition". ListPosition's role is to represent "The current position" in List, which allows many locations to be stored in the same serial. ListPosition is a partner of the List, so the inside of the List can hide the outside world (otherwise the LIST will be disclosed by its public operation behavior).

Note: ListPosition can be loaded more than an operator, like Advance (), backup (), because the operator is multi-loaded only the syntax coating of normal operation behavior. [3] Treat the entire position processing as a primary event (Atomic Event), built a class template to cover the event. It does not use public access operations in the internal cycle (it may be a virtual function), so efficiency can improve. Unfortunately, your application will have some additional binary code because Template is in a spatial exchange time. For more information, please see [Koenig, "Templates As Interfaces," JOOP, 4, 5 (SEPT 91)], and [Stroustrustrup, "The C Programming LanguageSecond Edition," Under "Compare"]. ====== ============================================ q117: "Template" intention? Template is integrated to a pressed cake mold, which is compressed to almost one look (although the raw material of the biscuit is not the same, they have the same basic shape). Similarly, Class Template is a sample mold that describes how to make the same basic type of a series of object categories; and Function Template is used to describe a series of functions that look similar. Class Template is often used in manufacturing, non-safe containers (even if this is only "how to use it"). ================================================== q118: "Function Template" syntax / language What is it? Consider this exchange of two integer from the variables: void swap (int & x, int & y) {int TMP = x; x = y; y = TMP;} If we want to exchange float, long, string, set and filesystems, We have to write the same procedure code that is roughly different, only different types of procedures, have enough annoying.

This repeatability of this unfunny is is the professional expertise, so we came up with Function Template: Template Void Swap (T & X, T & Y) {T TMP = X; X = Y; Y = TMP;} Every time we use "SWAP ()", the compiler will find the above definition and create another "template function" to be treated as its "case" (Instantiation). Such as: main () {INT I, J; /*...*/ swap (i, j); // Case "int" Swapfloat A, B; /*...*/ SWAP (A, B ); // Case "float" Swapcha C, D; /*...*/ Swap (C, D); // Case "char" swapstring s, t; /*...*/ swap (s, t); // Case "String" SWAP} (Note: "Template Function" is a case after "Function Template" physical system.) =============== ========================= q119: "Class Template" syntax / language is? Considering container categories like a plurality of arrays: // This will put in header like "array.h" Class Array {public: array (int LEN = 10): LEN_ (LEN), DATA_ (New Int " Len]) {} ~ array () {delete [] data_;} int LEN () const {return len_;} const INT & OPERATOR [] (INT i) const {data_ [check (i)];} int & operator [] (INT i) {data_ [check (i)];} array (const array&); array & operator = (const array&); private: int LEN_; int * data_; int Check (INT i) const {IF (i <0 || I> = len_) Throw Boundsviol ("Array", I, LEN _); RETURN I;}}; like the aforementioned "SWAP ()", repeated for Float, CHAR, STRING, ARRAY-OF-STRING, etc. Duplicate design Array categories is very annoying.

转载请注明原文地址:https://www.9cbs.com/read-83341.html

New Post(0)