The C facing the object design is six years ago, when I was "Object-Oriented), I remembered nearly ten definitions. Six years later, I couldn't explain what "object-oriented" from doing the experience of writing some people. " Trendy terms "object-oriented analysis" and "object-oriented design" in software engineering are usually targeted for "demand analysis" and "system design" links. "Object-oriented" has a few university factions, just like Buddha, God and Allah define this world in their respective ways, and leave a bunch of books to explain this world. Some scholars suggested to find "objects": Analysis of the National Party's literati in order to fight Mao Zedong's "沁 园 春 · 雪" Lao Jiang looked at the moment: "Mother Hay, all have a smell of corrugation in the coffin." I saw a few thousand pages of software engineering information, finally found some "mentally wisdom", unable to understand "object-oriented" The theory, and I am awake "programming is the last word." There are many object-oriented programming languages, such as SmallTalk, Ada, Eiffel, Object Pascal, Visual Basic, C , etc. C language is most expensive because it is compatible with the C language and has the performance of C language. In recent years, a plenty of plenty of plenty of java is red to the object language, and many people call to use Java leather C life. I think Java is like a C , although it is not directly genetic, but also a few points. When I was playing in my body, I sprinkled with urine. Two people should not quarrel here. The book on the C programming is very large, this chapter does not speak C grammar, only some small programming. If I understand these little truths earlier, I can greatly improve the quality of hundreds of thousands of lines. 6.1 C Object-Oriented Program Design In Early Revolutionary Movie has such a role, "I am a party representative, I represent the party, I am the party." Later, he brought disaster to comrades. Will you use C programmers to know how to design object orientation? Do you not use C programmers to do not know how to design objects? Both may not. Just like the bad egg into the party, it may not be a good person after the party, and the good people do not necessarily become a bad egg. I am not afraid to tell the cricks, "C no master, C language has a master." After using C and C , I deeply regret that I am not a C language master, and I don't have anyone, I don't have anyone. Object-oriented programming. Like a lot of C programmers, I thought I have understood object-oriented programming when I enjoy the benefits of C syntax. Just like squeezing off the toothpaste, it is really violent. People don't understand the pinyin and speak Mandarin. If you know how to be pinyin, you will make Mandarin better. Do not understand object-oriented programming can also be programmed with C , and if you know the object-oriented program design, you will make a better C program better. This section describes three very basic concepts: "Class and Object", "Inheritance and Combination", "virtual functions and polymorphism". Understand these concepts, help to improve the quality of the program, especially to increase "reusability" and "expandability". 6.1.1 Classs and Object Objects (Object) are an instance of class (instance). If the object is more than a house, then the class is the design drawings of the house. So the focus of object-oriented programming is the design of the class, not the design of the object.
Categories can package data and functions together, where functions represent class behavior (or service). Class Provide Keyword Public, Protected and Private Use to declare which data and functions are public, protected or private. This can achieve the purpose of information hidden, that is, let the class only publicly have to let the outside world know, and hide all other content. We can't abuse the classes of the package, don't treat it as a hot pot, what is thrown in. Is the design of the class be centered or centered on behavior? Advocating the internal data structure of the "data-centered" dispatched class, they are used to writing the data of the private type in front, and writing the PUBLIC type function in the following, as shown in Table 8.1 (a). Advocating "Behavioral" dispatcher should provide what kind of service and interface, they are used to writing the PUBLIC type function in front, and writing the private type data in the back, as Table 8.1 (B) Indicated. Many C teaching books advocate "data-centered" when designing classes. I persist and suggesting that the reader "is centered on" when designing the class, the first considers what kind of function should be provided. Microsoft's COM specification is the interface design, and COM interface is equivalent to the public function of the class [Rogerson 1999]. In terms of programming, we don't doubt the style of Microsoft. It is easier to design isolated and difficult, and it is difficult to correctly design base classes and their assigns. Because some of the programmers don't know "inheritance", "Composition", "Polymorphism). 6.1.2 Inheritance and Combination If A is a base class, B is a derived class of A, then b will inherit a data and functions. The sample program is as follows: Class a {public: void func1 (void); void func2 (void);}; class b: public a {public: void func3 (void); void func4 (void);}; // examplemain () {B b; // b. A object B.func1 (); // b inherits the function func1b.func2 (); // b from a inherits func2b.func3 () ;func4 (); } This simple sample program illustrates a fact: C "inheritance" features can improve the reuse of the program. Because "inheritance" is too useful, it is too easy to use, it should be prevented from using "inheritance". We have to give "inheritance" to use rules: 1. If class A and class B are not related, it is not possible to make B inherit A function in order to make B function more. Don't think "White White Don't eat", let a good-end healthy youth to eat people to eat people. Second, if class B is necessary to use A function, then two cases are divided into consideration: (1) If the "a Kind of) is logically b is A, the function is allowed to inherit a. If a man (MAN) is a kind of human (human), the boy (BOY) is a man. Then the class Man can derive from class Human, and class BOY can derive from class Mana. The sample program is as follows: Class Human {...}; class man: public human {...}; class boy: public man {...}; (2) If the logic A is a "part of a part of), Allow B to inherit a function, but to combine B with A and other things.
For example, Eye, Nose, Mouth, Ear (EAR) is part of the head (HEAD), and the class HEAD should be combined by Eye, Nose, Mouth, EAR, not derived. The sample program is as follows: Class Eye {public: void look;}; class nose {public: void smell (void);}; class mouth {public: void Eat (void);}; class ear {public: void listen (void);}; // Correct design, lengthy program class head {public: void look {m_eye.look ();} void smell (void) {m_nose.smell ();} void eat (void ) {m_mouth.eat ();} void listen (void) {m_ear.listen ();} private: eye m_eye; nose m_nose; mouth m_mouth; ear m_ear;}; if head is allowed from Eye, Nose, Mouth, EAR derived So, then Head will automatically have LOOK, SMELL, EAT, LISTEN these features: // Error Design Class Head: Public Eye, Public Nose, Public Mouth, Public Ear {}; The above programs are very short and the operation is correct, but this The design is wrong. Many programmers have committed the design mistakes. A rooster pursued a hen who just got the egg, do you know why? Because the hens underwent the duck egg. This book 3.3 said that "Run the correct" program is not necessarily a high quality program, which is an example. 6.1.3 In addition to inheritance, another excellent feature of C is supported by other exceptions, that is, allowing the object to be used as an object of the base class. If A is a base class, B and C are a derived class of A, the parameters of the polymorphic function TEST are pointers A. Then the Test function can reference the objects A, B, and C. The sample program is as follows: Class a {public: void func1 (void);}; void test (a * a) {a-> func1 ();} Class B: public a {...}; Class C: public a {...} {A; B; C C; test (& a); test (& b); test (& c);}; What is the value of "polymorphism", plus virtual functions After the abstract base class, the power of "polymorphism" is displayed. C uses keyword Virtual to declare a function of virtual functions, derived class's virtual functions, the function of the virtual function.
The sample program is as follows: Class a {public: Virtual void func1 (void) {cout << "this is a :: func1 / n"}}; void test (a * a) {a-> func1 ();} Class B : public a {public: Virtual void func1 (virt) {cout << "this is b :: func1 / n"}}; class c: public a {public: Virtual void func1 (void) {cout << "this is C :: func1 / n "}; // exampleMAIN () {a a; b; c c; test (& a); // Output this is a :: func1test (& b); // Output this is B: : Func1test (& C); // Output this is c :: func1}; if the base class A is defined as follows: Class a {public: Virtual void func1 (void) = 0;}; then function func1 called pure virtual functions, contain The class of pure virtual functions is called an abstract base class. Abstract base classes are only in the form of a pure virtual function, and the specific function is implemented by derived class. Combined with "abstract base class" and "polymorphism" have the following highlights: (1) The application does not have to write function calls for each derived class, only need to process the abstract base class. This stroke called "changed to be changed", which can greatly improve the reuse of the program (this is a multiplexed interface design, not the multiplexed implementation). (2) The function of the derived class can be referenced by the base class pointer, which is backward compatible to improve the program's expansion and maintainability. The previously written program can be called in the future, but the program written in the future can be called in the previously written program. 6.2 Good programming styles of internal strength martial arts masters are often unilateral. Similarly, programming masters will not use Qumen to write programs. A good programming style is the premise of producing high quality programs. 6.2.1 Naming Constituent has a lot of people to programmatically use Pinyin to function or variables, do not explain that you are very patriotic, but will make people who use this procedure confused (Many southerners don't understand pinyin, I don't understand) . English is generally not too complicated in the program, and you should strive to be accurate. Hungarian nomenclature is advocated by Microsoft [Maguire 1993], although it is very cumbersome, it has become nature with habits. No one is forcing what nomenclature, but it should be done: Your program naming must be consistent.
The following is a naming convention I use when I have programmed: (1) Macro definition with uppercase letters, such as the max_length; (2) function is combined with the word starting with uppercase letters, such as setname, getName; (3) pointer variable plus Prefix P, such as * pnode; (4) BOOL variable adding prefix B, such as bflag; (5) INT variable I, such as iWidth; (6) Float variable plus F, such as fwidth; (7) Double variable plus prefix D, such as dwidth; (8) String String Str, such as strname; (9) enumerating variable plus modulus E, member variables of EDRAWMODE; (10) classes M_, such as m_strname, m_iwidth; for int, FLOAT, DOUBLE type variable, if the meaning of the variable name is very obvious, it is not prefixed to avoid cumbersome. For example, INT type variables I, J, K; Float type 3D coordinates (X, Y, Z), etc. 6.2.2 Using the assertrogram Generally divided into debug version and the Release version, the Debug version is used for internal debugging, and the Release version is issued to the user. Assert is a macro that works only on the Debug version, it is used to check the situation that "should not" happen. The following is a memory replication program. During the run, if the parameter of Assert is false, the program will abort (generally appearing on the dialogue, which means where ASSERT is indicated. // Copy the memory block void memcpy (void * pvtrto, void * pvfrom, size_t size) {void * PBTO = (byte *) PVTO; void * pbfrom = (byte *) PVFROM; assert (pvto! = Null&& PVFROM! = null; while (size - -> 0) * PBTO = * PBFROM ; return (pvto);} Assert is not a macro that is rushing together, in order not to be in the program's Debug version and the release version ASSERT should not have any side effects. So Assert is not a function, but a macro. Programmers can see Assert as a honey-impaired test means that can be safely used in any system state. I rarely compare the assertion of the procedure, but I don't know if the role of the assert is more depressed. You have been a lot of time, not to troubleshoot, but just to figure out what this error is. Sometimes, programmers can occasionally design errors. So if you can't figure out what is checked, it is difficult to judge that the error is in the program, or it appears in the assertion. Fortunately, this problem is very good, just add a clear annotation. This is an obvious thing, but there are very few programmers. This is better than a person in the forest, seeing a "dangerous" big brand on the tree. But what is dangerous? Do you want to fall? Is there a waste well? Is there a beast? This warning card is difficult to play an active effect unless it tells people "dangerous".
It is difficult to understand that it is often overlooked by programmers or even deleted. [MAGUIRE 1993] The following is a few principles using assertions: (1) Use asserts to capture illegal sites that should not occur. Do not confuse the difference between illegal conditions and error conditions, the latter inevitably exist and must be processed. (2) Use the assertion to confirm the parameters of the function. (3) When writing a function, it is necessary to perform a repeated examination, and ask: "What assumes I plan?" Once the assumption is determined, it is necessary to check the assumptions using the assertion. (4) General textbooks encourage programmers to perform anti-wrong programming, but remember that this programming style will hide errors. When performing anti-wrong programming, if the "impossible" thing does occur, you should use the assertion to conduct alarm. 6.2.3 New, Delete and Pointer In C , operator NEW is used to apply for memory, and operator delete is used to release memory. In the C language, the function malloc is used to apply for a memory, and the function free is used to release memory. Since C is compatible with C language, New, Delete, Malloc, Free is likely to be used together. New can do more things than Malloc, which can apply for the memory of the object, and Malloc can't. The pointers in C and C language are mighty, and it will bring disasters with faults. For a pointer P, if you use the new application, you must use Delete to be released. If you are using Malloc applications, you must use free without using delete. After using Delete or releases the memory referred to by using P, it should be immediately explicitly displayed as NULL to prevent an error in the next use of P. The sample program is as follows: void test (void) {float * p; p = new float [100]; if (p == null) return; ... // do sometyingdelete p; p = null; // Good programming style // You can continue to use pp = new float [500]; if (p == null) Return; ... // do sometying elselete p; p = null;} We also need to prevent "wild pointers", "wild pointer" is "garbage" "Memory pointer, main genes have two: (1) The pointer is not initialized. (2) The pointer points to the memory that has been released. This is the most defense, the sample program is as follows: Class a {public: void func (void) {...}}; void test (void) {a * p; {a a P = & a; // Note A life period} P-> func (); // p is "wild pointer", program error} 6.2.4 When defining a constant using const, Const is more flexible than #define. The constant defined with const contains data type, which can participate in logical operations. For example: const Int length = 100; // length is int type const float max = 100; // max is float type #define length 100 // length No type #define max 100 // Max None type In addition to defining constants, Const has two "protection" features: 1. The parameter values of the mandatory protection function do not change the following procedures, the function f does not change the value of the input parameter Name, but the functions G and H may change the value of the Name.
Void f (string s); // pass by valuevoid g (String & S); // pass by referencevoid h (string * s); // pass by pointermain () {string name = "DOG"; f (name); // Name value does not change G (Name); // Name value may change H (Name); // Name value may change} For a function, if it '&' or '*' type The parameter is only used, and the connection should be added before this parameter to ensure that the function's code does not change the value of the parameter (if the value of this parameter, the compiler will have an error warning). Therefore, the functions G and H in the above programs should be defined: Void G (const string & s); Void H (Const String * S); Second, the member function of the mandatory protection class does not change the value of any data member below, class The member function of Stack is only used for counting. To ensure that Count does not change any of the values of any data in the class, the function count should be defined as a Const type. Class Stack {public: Void Push; Void Pop (Void); INT Count (Void) const; // const type function private: int Num; int Data [100];}; int Stack :: count Void) const { Num; // Compiling errors, NUM values change POP (); // Compiling errors, POP will change the value of the member variable Return Num;} 6.2.5 Other recommendations (1) Do not write an over-complex The statement, the compact C / C code does not see the highly efficient machine code, but will reduce the understandability of the program, and the probability of the program will increase. (2) Do not write a function of multiple functions, in the return value of the function, do not mix the normal value and the error flag together. (3) Do not program the BOOL TRUE and FALSE corresponding to 1 and 0. Most programming languages define false as 0, and any non-zero is TRUE. Visual C defines TRUE to 1, and Visual Basic defines TRUE as -1. The sample program is as follows: BOOL FLAG; ... if (flag) {// do something} // correct usage if (Flag == true) {// do something} // Dangerous Usage IF (Flag == 1) {/ / do something} // dangerous usage if (! flag) {// do something} // correct usage if (Flag == false) {// do something} // unreasonable usage if (Flag == 0 ) {// do something} // unreasonable usage (4) Be careful not to write "= =" to "=", the compiler does not automatically discover such errors. (5) Do not write 123 to 0123, the latter is an octal value. (6) Record the programming errors that you often make, and make a table sticker next to the computer. 6.3 Small knot C / C programming is like the martial arts of Shaolin Temple, I have been in profound, I practiced for 8 years, probably just learn two or three%. So, whenever you don't think your programming level The world is the first, see someone else's good technology and style, you have to learn.