Talk about the initialization of C ++ (2)

zhaozj2021-02-16  59

Let's first look at the last legacy. Change the code in (1) to the comment section, maybe you don't know anything in a moment, but eventually, it is not yet, debugging throws anomalies, the information is as follows: Unpredited "System.Runtime.InterOpServices.seHexception "Type of exceptions appear in Testinit.exe

Other information: External components have an exception.

THIS Application Has Requested The Runtime To Terminate It in An Unusual Way.please Contact The Application's Support Team for more information.press any key to payter

I think, if you look back, you will understand why it is so (we must ask for a certain question :). What we have to talk about today is that some variables have only the only initial form. Through examples, tell you to pay special attention. Then, let's take a step in step and look at the problem of shallow copies. I believe that students C students will have some questions about the "copy function". It is to solve the above problems; but in fact, there is a hidden place, today I want to point out. These programs, but I specially designed. I hope that it can be very convenient to understand the problem, and solve the way.

First, see the first example. In the class, these two types of variables: E.G.Name & Name; // Reference const Int ID; // constant their initialization form is unique. And you must be initialized by you. Look at the procedure below: //human.h#pragma overce

Class name {char * name; public: //... }; Class Human {name & name; const Int; // Everyone is unique // ... public: human (void); ~ human Void); //... }//human.cpp#include "human.h" #using

// Default constructor human :: human (void) {}

Human :: ~ human (void) {}

Write a primary file test. But debugging error, error information file is: / * --------------------------------------- ------------------------------------- // Human: error file ------ Start generation: Project: Testinit, Configuration: Debug Win32 ------

Compiling ... human.cpphuman.cpp (5): Error C2758: "Human :: Name": E: / Net / Small_code / Testinit / Human must be initialized in the constructor base / member initial value setting list. H (13): See "Human :: Name" declaration human.cpp (5): Error C2758: "Human :: id": must initialize E: / NET in the list list must be initialized in the constructor base / member initial value set item /Small_code/testinit/human.h (14): See "Human :: id" declaration fmain.cppdate.cpp is generating code ...

Generating logs Save in "File: // E: /Net/small_code/testinit/debug/buildlog.htm" Testinit - 2 error, 0 warning

------------------------------------------- Generate: 0 has been successful, 1 has failed, 0 has been skipped ------------------------------------------------------------------------------------------------------------------------------------------------ -------------------------------------- * / Because here involve only C grammar, I don't have much tongue, how to correct it, I hope you can do it, you must do it, don't think about it ~~~ Of course, if you are a problem, I think you can learn this: Design C language Why do you have a default initialization, but they cannot; deliberately provide them with intra-type initialization, from the compilation perspective?

Let's talk about what is the shallow copy of resources. The habit of hitting C, C is unified to the system self-allocated resources, but the user applies for resources, there is a user to release. For example:

Usertype * p = new usepepe (/ * --- * /); // ... delete p; // delete release is generally unforgettable

Separate variables may not be problematic for you. But in the class, these situations are quite complicated. Do not handle it, your system is still because of memory leaks, or it is an abnormally frequently occurred. Let's first look at some of the default operations of C : // ... class oneclass {int _view; public: oneclass (int _val = 0): _ value (_val) {} ~ oneClass () {}

// ...};

// you may use in this way: OneClass OneObj (7); OneClass Anotherobj; Anotherobj = OneObj; // (1) // ... // Int Compare (OneClass One, OneClass TWO); Int K = Compare (OneObj , AnotherObj); // (2) // ...

Under the scene of this program, the above code is working well, but what did you know (1) and (2) system? Do you know that if your initialization is not good, even, you can take the above initialization habits, your program is easy to collapse. The answer is that the (1) statement is executed, the default, the system attempts to put oneObj's resource all COPY, but the user applied for resources (New :), but incoming address; (2) The default shape of the statement; Pass in the same rules. Of course, this is different from Java and C #, because Java and C # objects are reference types. And C unless you are forcibly defined as the reference type, it is not.

Let's take a look at the examples, I suggest you only look at the program, don't look down, see if you can find any problems.

//human.h #pragma overce

#define null 0

Class name {char * name; public: name (char * _name = null): name (_name) {} ~ name () {} char * getName () {return name;}

}; class human {name * name; // int ID; // Uniqueizes Sign Public: human (int ID = 0, char * _NAME = null); ~ Human (Void);

Int getId () const {return id;} name * getname () {return name;}}

//human.cpp#include "human.h" #using

Human :: human (int id, char * _name): id (id) {name = new name (_name); // Initialization: pointer}

Human :: ~ human (void) {delete name; // Release resources when sect

//fmain.cpp#include #include "human.h"

Void main () {// Test program try {human lily (11100120, "lily"); human lucy = lily;} catch (...) {// If there is any anomaly std :: cout << "/ n unknown Exception ... / n ";}}

/ / Please look back in the program, do you think everything is fine?

In fact, during the debugging process, after the three exceptions are ignored, you will get the following results: / * after Three Exceptions Occured you get:

UNKNOWN EXCEPTION ... PRESS ANY Key to Continue

* / Why? See these lines of code: Human Lily (11100120, "Lily"); human lucy = lily; although I gave a small example, the form is the same, that no problem. Why don't you? Because the definition of the class is different. Mechanism of C , this line human Lucy = Lily; is a copy of Lily to Lucy (Lucy is not called constructor), but because of where Name is the user's application, it cannot copy it. However, it passed the address directly. This way, you know, Lucy.Name and Lily.name are the same. Thus, when a destructor is called, the resources pointed to by Name have been released. And another sectoral function is released, the problem is coming - the program crashed! This is a shallow copy issue - "shallow" incomplete copy :). We will do the reason. The solution is to do it yourself! Write a copy assignment (PUBLIC):

The form is: classname & operator = (classname & obj) {/*...*/} You can see the following solutions and results: / *

IF you add ... in class human:

Human & human = (hum! = & Human) {id = human.getid (); name = new name (human.getname () -> getName ()); return * this;}} OK, AND YOU GET: PRESS ANY Key to Continue

That is what we want! * / The following example is the problem of copying functions. On the basis of the above, I changed the structure of the program and defined a name space. Specific problem analysis I left next time, you have the opportunity to look at it. Are you clear? Can you solve this problem?

//human.h#pragma overce # Using namespace humanbeing {#define null 0

Class name {char * name; public: name (char * _NAME = null): name (_name) {} ~ name () {}

Char * getname () {return name;}

}; class human {name * name; // int id; // Unique logo public: human (int id = 0, char * _NAME = null): ID (ID) {name = new name (_name); // Application Resources} ~ human (void) {delete name; // Release Resource}

// Copy value Human & Operator = (human & human) {IF (this! = & Human) {id = human.getid (); name = new name () -> getName ()); return * this; }}} Int getId () const {return;} name * getname () {return name;}}

//// one, human another {if (one.getid () == another.getid ()) Return True; Else Return False;}

}

// Test file #include #include "human.h" void main () {Using Namespace HumanBeing; try {human lily (11100120, "lily"); human lucy = lily;

IF (iSSameman (Lucy, Lily) {std :: cout << "/ n"} else std :: cout << "/ n no're not the same one. / N ";

} Catch (...) {std :: cout << "/ n unknown exception ... / n";}}

Debug results, it is after six unusual, appears: after Six Exceptions Occured you get:

....

UNKNOWN EXCEPTION ... PRESS ANY Key to Continue

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

New Post(0)