C + + learning starts from scratch (v)

Source: Internet
Author: User
Tags constructor modifier

This article explains what is left of the custom type and explains the semantics.

Permissions

The provision of member functions, which enables the semantics of custom types to be elevated from resources to functional resources. What is a functional resource? for example, to map a radio to a number, you need to map the operation to adjust the frequency of the radio to receive different stations, adjust the volume of the radio, turn on and off the radio to prevent the loss of power. To do this, the radio should be mapped to a structure similar to the following:

struct Radiogram

{

Double Frequency; /* Frequency/void Turnfreq (double value); Change frequency

float Volume; /* Volume/void Turnvolume (float value); Change the volume

float power; /* Power */void Turnonoff (bool bOn); Switch

BOOL Bpoweron; Whether to open

};

The above radiogram::frequency, Radiogram::volume, and Radiogram::P ower because they are defined as members of the structure Radiogram, their semantics are the frequencies of a radio, The volume of a radio and the power of a radio. The other three member functions also have the same semantics to change the frequency of a radio, to change the volume of a radio, and to turn on or off a radio. Pay attention to this "a", indicating which radio is not yet known, only through the member operator to the left of a specific radio and they are not known which radio, this is why they are called the offset type. This is explained in more detail in the next article.

Note the question: Why do you want to map the three actions that you just made to a member function of the struct Radiogram? Because the radio has such a function? So for the selection of watermelon, watermelon and watermelon, do you want to define a structure, and then give it three select, cut, eat the member function?? Isn't it absurd? The three operations of the former are for the member variables of the struct, and the latter is for the structure itself. Then change to eat fast food, eat a fast-food hamburger, eat fast-food fries and drink fast-food cola. If the two eating and a drinking operation becomes a member function of fast food, is that the function of fast food?! This is actually the problem of programming ideas, and here is the so-called object-oriented programming idea, although it is a very good idea, but it is not necessarily appropriate, the next chapter will be discussed in detail.

The reason we call the radio switch is function, because in fact, we can not directly change the frequency of the radio, we must rotate the selection of the knob to change the frequency of reception, the same, the volume is also adjusted by adjusting the volume knob to achieve, and due to the power-on caused by the power drop is not directly caused by us, But indirectly by listening to the radio. Therefore, the above radiogram::P ower, radiogram::frequency and other member variables have a special feature-outside, this radio things can not change them. For this reason, C + + provides a syntax to implement this semantics. In the type-definition character, give the format:< permission:. The < rights here > as one of the public, protected, and private, respectively, are known as common, protected, and proprietary, as follows:

Class Radiogram

{

Protected:double m_frequency; float M_volume; float M_power;

Private:bool M_bpoweron;

Public:void turnfreq (double); void Turnvolume (float); void Turnonoff

(bool);

};

It can be found that it is the same as the previous label definition format, but is not a statement modifier, that is, you can struct abc{private:}; There is no need to be in private: Follow the statement because it is not a statement modifier. Starting from it, until the next such syntax, all declarations and definitions between the member variables or member functions have the semantics it represents. For example, the above class Radiogram, where the radiogram::m_frequency, Radiogram::m_volume, and radiogram::m_power are protected member variables, RADIOGRAM::M_ Bpoweron is a private member variable, and the remaining three member functions are public member functions. Note that the above syntax can be repeated, such as: struct ABC {public:public:long A; private:float b; Public:char D;.

What do you mean? Very simple, public members of the outside world can be accessed, protected members outside the external access, private members of the outside and subclasses can not access. The following is a description of the subclass. Look at the public first. For the above.

The following will be an error:

Radiogram A; A.m_frequency = 23.0; A.m_power = 1.0f; A.m_bpoweron = true;

Because the three operations on a above all use the protection of a or private members, the compiler will make an error, because the two members of the outside world are inaccessible. and A. Turnfreq (10); There is no problem, because the member function radiogram::turnfreq is a public member and can be accessed by the outside world. What do you mean by the outside world? For a custom type, the function of the member function of this custom type is called the outside world where all the code can be written outside of the body. Therefore, for the above Radiogram, only its three member functions can access its member variables in the body. That means the following code will be fine.

void Radiogram::turnfreq (Double value) {m_frequency + = value;}

Because the m_frequency is used in the Radiogram::turnfreq function body, does not belong to the outside world.

Why do you do that? The semantics of the first expression. First, the above definition of a member as public or private has no effect on the resulting code. Then, I said before the adjustment of the receiver frequency is by adjusting the capacity of the harmonic capacitance of the radio to achieve, the capacity of the capacitance of the person must use components to do, and will receive the frequency map to the number, because it is a number, the CPU can be modified. If the direct a.m_frequency + + 10; To modify, on the meaning of the code, it is: the person who executes this method increases the reception frequency of the radio 10KHz, which is against our objective world, and the previous semantics. So as a way to provide it as a grammar, to be reviewed by the compiler, we can write code that is more in line with the semantics of the world we live in.

Note that you can union ABC {long A; Private:short b;. Is it public or protected before the abc::a here? I believe it is public, and that's why I've always used struct and union to define a custom type, as I've seen so many examples from the previous example. Otherwise the previous example will be an error. And the previous article said that there is only one small difference between structure and class, that is, when a member is not decorated, for a class, that member will be private rather than public, that is, the following error.

Class ABC {long A; private:short b;}; ABC A; A.A = 13;

Abc::a is considered private because of the previous class. From this point, you can see that structs are used to map resources (resources that can be used directly), and classes are used to map resources that have functionality. The next chapter will discuss their semantic differences in detail.

Construction and deconstruction

Knowing the things mentioned above, it is clear that there are the following questions:

struct ABC {Private:long A, b;}; ABC A = {10, 20};

Does the initialization assignment variable A above be correct? Of course it's a mistake, otherwise it's a loophole in grammar (the outside world can change the members that cannot be modified). However, there are times when it is necessary to initialize to ensure some logical relationships, for which C + + proposes the concept of construction and deconstruction, respectively, corresponding to initialization and cleanup work. Before we get to this, let's take a look at what's called an instance (Instance).

An instance is an abstract concept that represents an objective existence, which is closely related to the concept of "the world" as introduced in the next chapter. For example: "This is the table" and "This table", the former "table" is a kind, the latter "table" is an example. There are 10 sheep here, saying there are 10 examples of sheep, and sheep is only one type. Can simply be considered as an object of the objective world, the human for the convenience of the various objects are divided into classes, so give the TV description does not give a television example, and a television is given a TV example. Again, the code for the program is not very meaningful, and only when it is executed, we call an instance of that program running. If the operating system is required to perform it before it is finished, for a multitasking operating system, you can say that two instances of that program are being executed, as if two word files were viewed at a point in time, and two instances of the Word program are running.

In C + +, only the number that can be manipulated, a number is an instance (as can be seen in the next note), and more generally, the address of the memory that identifies the record number is an instance, that is, the variable is an instance, and the corresponding type is the kind of object mentioned above. For example: Long A, *pa = &a, &ra = A;, this generates two instances, one is a long instance, the other is an instance of long* (note that since RA is long&, an instance is not generated, but RA is still an instance). Similarly, for a custom type, such as: Radiogram AB, c[3], it is said that four Radiogram instances were generated.

For instances of a custom type, the corresponding constructor is invoked when it is generated, and the corresponding destructor is invoked when it is destroyed. Who's going to call? The compiler is responsible for helping us write the necessary code to implement the corresponding constructs and destructors calls. The stereotype of the constructor (that is, the type of the function name, such as float AB (double, char), and the prototype for float (double, char)) is the format of the type name of the custom type directly as the function name, no return value type, and the argument is random. For destructors, the prefix "~" preceded by the corresponding type name has no return value type and must have no parameters.

As follows:

struct ABC {ABC (); ABC (long, long);

~ABC (); bool Do (long);

Long A, count; float *PF; };

Abc::abc () {a = 1; count = 0; PF = 0;}

ABC::ABC (Long tem1, long tem2)

{a = tem1; count = tem2; PF = new float[count];

Abc::~abc () {delete[] PF;

BOOL ABC::D O (Long cou)

{

float *p = new float[cou];

if (!p)

return false;

Delete[] PF;

PF = p;

Count = Cou;

return true;

}

extern ABC G_abc;

void Main () {ABC A, &r = A; a.do (10);

{ABC B (10, 30);}

ABC *p = new ABC[10];

Delete[] p; }

ABC G_a (a), g_p = new abc[5];

The above structure ABC defines two constructors (note that there are two overloaded functions), and the names are ABC::ABC (the compiler will actually be converted to different symbols for the connection). Also defines a destructor (note that only one can be defined, because it must have no parameters and cannot be overloaded), the name is ABC::~ABC.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.