Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use C++ object-oriented Design

2025-04-05 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article is to share with you about how to use C++ object-oriented design. The editor thinks it is very practical, so I share it with you. I hope you can get something after reading this article. Let's take a look at it with the editor.

The fashionable terms "object-oriented analysis" and "object-oriented design" in software engineering are usually aimed at "requirements analysis" and "system design". There are several schools of "object-oriented", just as the Tathagata Buddha, God, and Allah define the world in their own ways, leaving behind a bunch of scriptures to explain the world.

Some scholars suggest finding "objects" like this: analyze the grammar of a sentence and find out nouns and verbs. Nouns are objects and verbs are object methods (that is, functions).

In order to counter Mao Zedong's "Spring Snow in Qinyuan", the Kuomintang literati specially asked the Qing Dynasty survivors to write some neat poems to Chiang Kai-shek. Lao Chiang scolded angrily, "Niang Hipi, there is a smell of rotting corpses in the coffin." After reading thousands of pages of software engineering materials, I finally found that I was somewhat "mentally retarded" and could not understand the "object-oriented" theory. At the same time, I realized that "programming is the last word."

There are many object-oriented programming languages, such as Smalltalk, Ada, Eiffel, Object Pascal, Visual Basic, C++ and so on. C++ is the most popular language because it is compatible with C and has the performance of C. In recent years, a pure object-oriented language called Java has become so popular that many people are clamoring to use Java to revolutionize C++. I think Java is like C++ 's nephew, although not directly inherited, but also somewhat decent. The nephew took a piss while playing on his uncle, and the two should not quarrel about it.

1. Important Concepts of C++ object-oriented programming

There is such a character in the early revolutionary film, he said: "I am the representative of the party, I represent the party, I am the party." Later he brought disaster to his comrades.

Do programmers who can use C++ must know object-oriented programming?

Must programmers who can't use C++ don't know object-oriented programming?

Not necessarily either. Just as bad guys may not be able to become good people after joining the Party, good people may not become bad guys if they do not join the Party.

I am not afraid to offend the public to say a big word: "C++ does not have a master, the C language has a master." After 8 years of programming in C and C++, I deeply regret that I am not a master of the C language, and that no one has asked me how to do object-oriented programming. Like many C++ programmers, when I enjoy the benefits of C++ syntax, I think I already understand object-oriented programming. It's like squeezing out toothpaste to sell toothpaste skin. It's a real disaster.

People can speak Putonghua even if they don't know Pinyin. If they know Pinyin, they can speak Putonghua better. Do not understand object-oriented programming can also use C++ programming, if you know object-oriented programming will be better C++ programming. This section covers three very basic concepts: "classes and objects", "inheritance and combination", and "virtual functions and polymorphism". Understanding these concepts helps to improve the quality of programs, especially "reusability" and "expandability".

1.1 classes and objects

An Object is an instance of a class (Class) (Instance). If the object is compared to a house, then the class is the design drawing of the house. Therefore, the focus of object-oriented programming is the design of classes, not the design of objects. A class can encapsulate data and functions, where the function represents the behavior (or service) of the class. Class provides the keywords public, protected, and private to declare which data and functions are public, protected, or private.

In this way, the purpose of information hiding can be achieved, that is, the class can only expose what must be known to the outside world, while hiding everything else. We should not abuse the encapsulation function of the class, do not regard it as a hot pot and throw everything into it.

Is the design of the class data-centric or behavior-centric?

The "data-centric" group is concerned about the internal data structure of the class. They tend to write data of type private first and functions of type public at the end, as shown in Table 8.1 (a).

The "behavior-centric" group is concerned about what kind of services and interfaces classes should provide, and they are used to writing functions of type public first and data of type private later, as shown in Table 8.1 (b).

Talking about the experience of object-oriented Design of C++ for 8 years

Many C++ teachers advocate being "data-centric" when designing classes. I insist and advise readers to be "behavior-centric" when designing classes, that is, to consider what functions the class should provide first. The core of Microsoft's COM specification is interface design, and the interface of COM is equivalent to the public function of the class [Rogerson 1999]. In terms of programming, let's not doubt the style of Microsoft.

It is easy to design isolated classes, but it is difficult to design base classes and their derived classes correctly. Because some programmers do not understand the concepts of "Inheritance", "Composition" and "Polymorphism".

1.2 inheritance and combination

If An is the base class and B is a derivative of A, then B will inherit A's data and functions. The example program is as follows:

Class A {public: void Func1 (void); void Func2 (void);}; class B: public A {public: void Func3 (void); void Func4 (void);}; / / Example int main () {BB; / / an object b.Func1 () of B; / / B inherits the function Func1 b.Func2 () from A; / / B inherits the function Func2 b.Func3 () from A; b.Func4 (); return 0;}

This simple example program illustrates the fact that C++ 's inheritance feature can improve the reusability of the program. It is precisely because "inheritance" is too useful and easy to use that it is necessary to prevent the misuse of "inheritance". We need to set some rules for the use of inheritance:

First, if class An and class B are not related, you can't let B inherit the function of An in order to make B have more functions.

Do not think that "do not eat for nothing", let a healthy young man eat people to replenish his body for no reason.

Second, if it is necessary for class B to use the function of A, it should be considered in two cases:

(1) if B is logically a "a kind of" of A, B is allowed to inherit the function of A. For example, Man is a kind of Human, while Boy is a kind of man. Then class Man can be derived from class Human, and class Boy can be derived from class Man. The example program is as follows:

Class Human {... }; class Man: public Human {… }; class Boy: public Man {… }

(2) if An is logically a "a part of" of B, B is not allowed to inherit the function of A, but to combine B with An and other things. For example, the Eye, Nose, Mouth, and Ear are part of the Head, so the class Head should be composed of classes Eye, Nose, Mouth, and Ear, not derived. The example program is as follows:

Class Eye {public: void Look (void);}; 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 (void) {m_eye.Look ();} void Smell (void) {m_nose.Smell () } void Eat (void) {m_mouth.Eat ();} void Listen (void) {m_ear.Listen ();} private: Eye masks; Nose masks; Mouth masks; Ear masks;}

If Head is allowed to derive from Eye, Nose, Mouth, Ear, then Head will automatically have the functions of Look, Smell, Eat, Listen:

/ / wrong design class Head: public Eye, public Nose, public Mouth, public Ear {}

The above program is short and works correctly, but the design is wrong. Many programmers can't stand the temptation of "inheritance" and make design mistakes.

A rooster chased a hen that had just laid eggs. Do you know why?

Because the hen laid duck eggs.

1.3 Virtual functions and polymorphisms

In addition to inheritance, another excellent feature of C++ is its support for polymorphism, which allows objects of a derived class to be used as objects of a base class. If An is the base class and B and C are derivative classes of A, the argument to the polymorphic function Test is the pointer to A. Then the Test function can refer to objects A, B, and C. The example program is as follows:

Class A {public: void Func1 (void);}; void Test (A * a) {a-> Func1 ();} class B: public A {… }; class C: public A {… }; / / Example int main () {An a; B b; C c; Test (& a); Test (& b); Test (& c); return 0;}

The above programs do not see the value of "polymorphism". After adding virtual functions and abstract base classes, the power of "polymorphism" is shown.

C++ uses the keyword virtual to declare a function as a virtual function, and the virtual function of the derived class will (override) the function of the corresponding virtual function of the base class. The example program is as follows:

Class A {public: virtual void Func1 (void) {coutFunc1 ();} class B: public A {public: virtual void Func1 (void) {coutFunc (); / p is "wild pointer", program error}

2.4 using const

Const is more flexible than # define when defining a constant. Constants defined with const contain data types that 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 untyped # define MAX 100 / / MAX untyped

In addition to defining constants, const has two "protection" functions:

1. The parameter values of the forced protection function will not change.

In the following program, function f does not change the value of the input parameter name, but both functions g and h may change the value of name.

Void f (String s); / pass by value void g (String & s); / / pass by referance void h (String * s); / / pass by pointer int main () {String name= "Dog"; f (name); / / the value of name does not change g (name); / / the value of name may change h (name); / / the value of name may change return 0;}

For a function, if a parameter of type'&'or'*'is used for input only, not for output, you should precede the parameter with const to ensure that the function's code does not change the value of the parameter (the compiler will give an error warning if you change the value of the parameter). Therefore, the functions g and h in the above program should be defined as:

Void g (const String & s); void h (const String * s)

Second, force the member function of the protection class not to change the value of any data member

In the following procedure, the member function Count of class stack is used for counting only. To ensure that Count does not change the value of any data members in the class, the function Count should be defined as const.

Class Stack {public: void push (int elem); void pop (void); int Count (void) function of type const; / / const private: int num; int data;}; int Stack::Count (void) const {+ + num; / / compilation error, num value changes pop (); / / compilation error, pop will change the value of member variable return num;}

2.5 other suggestions

(1) do not write an overly complex statement, compact Candlespace C code can not get efficient machine code, but it will reduce the understandability of the program, and the probability of program errors will be increased.

(2) do not write a function that integrates multiple functions, and do not mix the normal value with the error flag in the return value of the function.

(3) do not program the BOOL values TRUE and FALSE corresponding to 1 and 0. Most programming languages define FALSE as 0, and any non-zero value is TRUE. Visual C++ defines TRUE as 1, while Visual Basic defines TRUE as-1. The example 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 "=" as "=", the compiler will not automatically find this error.

(5) do not write 123as 0123, which is an octal value.

(6) record the programming mistakes you often make, make a table and stick it next to the computer.

The above is how to use C++ object-oriented design. The editor believes that there are some knowledge points that we may see or use in our daily work. I hope you can learn more from this article. For more details, please follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report