[Basic-C + + Foundation-surprise written test] 8. Class

Source: Internet
Author: User
Tags access properties

Overview:

Well-designed class types can be as easy to use as built-in types 0.0

This part will be more boring, are some basic concept understanding t.t

  

8.1 Access designator

Class has the following two types of access to its members:

1) Internal access: The CREATE function in the class accesses the members of the class.

2) Object access: Outside the class, access to the members of the class through the object of the class.

The members of a class can have public, protected, private three access properties, member functions of the class ( internal access ), and friend functions can access all members of the class, but outside the class through the object of the class ( object access ), You can only access the common members of the class.

Introduction to Class 8.2 members

8.2.1 member functions

The calling member function is actually called using an object. Each member function (except the static member function) has an additional, implicit formal parameter, this. When the member function is called, the parameter this is initialized to the address of the object that called the function.

8.2.2 constructor function

A constructor is a special member function that has the same name as a class, has no return type, and can have multiple constructors, each of which must have a different number or type of parameters due to other constructors.

If the default constructor is automatically generated using the compiler:

1) class member: Runs the default constructor of the type to initialize.

2) The initialization value of a member of a built-in or composite type depends on the scope of the object: in the local scope, these members cannot be initialized, and in global use they are initialized to 0.

Member Initialization list

In C + +, the order in which member variables are initialized is the same as the order in which they are declared in the type, regardless of their order in the constructor's initialization list :

classA {Private:    inti; intJ; Public: A (): J (0), I (j +2) {}    voidprint () {cout<<"I:"<<i<<", J:"<<j<<Endl; }};intMainvoid) {A A;    A.print (); return 0;}

So the above example, I is initialized first, and the parameter J of initialization I is not initialized, is a garbage value, so I is a garbage value. When initializing J, it is initialized according to parameter 0, so j = 0.

Some data members must be initialized in the constructor initialization list : A member of a class type without a default constructor, and a member variable of a const type and a member variable of a reference type.

Copy constructor (copy constructor)

The copy constructor, assignment operator, and Destructor are always referred to as replication controls. The compiler automatically implements these operations, but the class can also define its own version.

Definition: Only a single parameter, and the parameter is a reference to the object of this class type (commonly used const adornments).

The role of the copy constructor:

1) Initializes an object based on another object of the same type.

2) Copy an object, pass it as an argument to a function, or copy an object when returning from a function:

classMyclass { Public: Myclass (intN) {number =N;} Myclass (ConstMyclass &others) { number=Other.number; Count<<"a"; }Private:    intNumber ;};voidFun (Myclass p) {Myclass temp (p);}intMainvoid) {Myclass obj1 (Ten), Obj2 (0);    Myclass obj3 (OBJ1);    Fun (OBJ3); return 0;}

In the above code, three copy constructors are called, the first is Myclass obj3 (obj1) in Main, the second is the argument obj3 to the fun parameter p, and the third is the "Myclass Temp (p) in the function fun". Statement.

3) Initialize the elements in the sequential container.

4) initializes the array element according to the element initialization list.

8.2.3 Destruction function

Destructors can be used to dispose of resources that are acquired during the construction of an object or during the life of an object. The compiler automatically executes destructors for non-static data members of the class, regardless of whether the class defines its own destructor.

Look at an example of what the following code output is:

classA { Public: A () {cout<<"A";} ~a () {cout<<"~a";}};classb{ Public: B (A&a): _a (a) {//_a (a) called the copy constructorcout<<"B"; }    ~b () {cout<<"~b";}Private: A _a;};intMain () {a A;//The constructor is called automatically when the object is definedb b (a);//copy constructor for call a before output B    return 0;} 

Output: Ab~b~a~a. The structure of the object is constructed by reverse order. For a composite object, the main object is first refactored and the object it contains is then refactored. The construction process is: A a B, then the destructor must be symmetric B a A. Instead, the copy constructor uses the automatically generated version of the system, with no output.

8.2.4 the call order of constructors and destructors

1. Single Inheritance

When derived, constructors and destructors cannot be inherited, and in order to initialize a base class member, the constructor and destructor must be redefined on the derived class, and the constructor of the base class is called in the initializer list of the constructor.

The general format of a derived class constructor is:

derived class name (General Staff tables): base class Constructor (parameter table    ) {//  function Body };

The constructor of the base class must be placed in the initialization list of the derived class to call the base class constructor to complete initialization of the base class data member (if none, call the base class default constructor), and the derived class constructor is called in the following order:

1) The completion of the entire block of memory for the object, which is generated automatically by the system when the constructor is called.

2) Call the constructor of the base class to complete the initialization of the base class member.

3) If a derived class contains an object member, a const member, or a reference member, it must complete its initialization in the initialization table.

4) The derived class constructor body executes.

When the object is deleted, the destructor of the derived class is executed. Destructors cannot be inherited, so when you execute a derived class destructor, the base class destructor is called automatically. The order of execution is to execute the destructor of the derived class first, and then the destructor of the base class, which is the reverse of the order in which the constructor was executed.

Look at the following questions, notice the difference between the above questions, here are the inheritance:

classA { Public: A () {cout<<"A";} ~a () {cout<<"~a";}};classD | Publica{//Single Inheritance Public: B (A&a): _a (a) {cout<<"B"; }    ~b () {cout<<"~b";}Private: A _a;};intMain () {a A;     b b (a); return 0;} 

The output is: Aab~b~a~a~a.

2. Multiple inheritance

When multiple inheritance occurs, the constructor initialization list for the derived class requires calling the constructors of each base class.

Note: The constructor initialization list now controls only the values used to initialize the base class, and cannot control the construction order of the base class. The constructor of the base class is called in the order in which the base class constructor appears in the derived list.

3. Virtual inheritance

The constructor of the virtual base class is called first, and if there are multiple virtual base classes, the order of the virtual base class constructors is the order in which this virtual base class appears in the current derived class instead of the order in which they are in the Member initialization table.

8.2.5 operator Overloading

The operator overloads a function whose name is operator followed by the symbol of the operator that is defined.

Note: There are four operators that cannot be overloaded: "::", ". *", ".", "?:", simple memory, with "dot" can not ^_^

Assignment operator overloading

Places to be aware of:

1) Declare the type of the return value as a reference to that type and return the reference to the instance itself (that is, *this) before the function ends.

2) The type of the parameter passed in is declared as a constant reference.

3) Remember to release the memory that the instance itself has.

4) Determine if the passed in parameter is the same instance as the current instance (*this).

Here is an example:

//Statementclasscmystring{ Public:        //omitting constructors and destructors ...cmystring& cmystring::operator=(ConstCMyString &str); Private:    Char*m_pdata;}//What you have added:cmystring& cmystring::operator=(ConstCMyString &str) {    if( This= = &str)return* This; Delete[]m_pdata; M_pdata=NULL; M_pdata=New Char[Strlen (Str.m_pdata) +1];    strcpy (M_pdata, str.m_pdata); return* This;}

Output Operators << overloads

The output operator should accept ostream& as the first parameter, a reference to the class-type const object as the second parameter, and return a reference to the Ostream parameter, which is simply defined as follows:

operator Const ClassType &Object) {    os<<//    return os;}

operator new vs. operator delete Overloads

You cannot redefine the behavior of the new and delete expressions, which can be overloaded with global functions operator new and operator delete.

New execution: First, call the standard library function named operator new, allocate the original untyped memory large enough to hold an object of the specified type, and next, run a constructor of that type, construct the object with the specified initializer; Returns a pointer to the newly assigned and constructed object.

Delete execution: First, run the appropriate destructor on the object it points to, and then release the memory of the object by calling the standard library function named operator delete.

As in the following example:

classX { Public: X () {cout<<"Constructor"}; Static void*operator New(size_t size) {cout<<"New"; return::operator New(size); }    Static void operator Delete(void*pointee) {cout<<"Delete"; ::operator Delete(pointee); }    ~x () {cout<<"destructor"};};intMainvoid) {x* px =NewX (); Deletepx; return 0;}

The output is "new constructor destructor Delete".

8.3 Overloading, overwriting, and hiding of member functions

8.3.1 Overloading

1) The same range (in the same class);

2) the same function name;

3) different parameter lists;

4) The virtual keyword is optional.

8.3.2 Coverage

Overriding a function with the same name in a base class in a derived class requires that the base class must be a virtual function and:

1) has the same number of parameters as the virtual function of the base class;

2) has the same parameter type as the virtual function of the base class;

3) The same return type as the virtual function of the base class: either the same as the base class virtual function, or both the pointer (or reference), and the pointer (or reference) type returned by the derived class virtual function is the subtype (derived type) of the pointer (or reference) type returned by the substituted virtual function in the base class.

As below, the fun1 in B covers the fun1 in a:

class A {public:    virtualvoid fun1 (intint) {}}; class  Public A {public:    void fun1 (intint) ()};

Note: In the overriding method, the calling method body is determined by the type of the object, and the overloaded relationship selects the method body based on the argument table and formal parameter list at the time of invocation.

8.3.3 Hidden

Hiding means that in a special case, a function in a derived class masks a function of the same name in the base class, including:

1) Two function parameters are the same, but the base class is not a virtual function.

2) Two function parameters are different, regardless of whether the base class function is a virtual function, the base class function will be masked.

This part is written here, welcome to all the hands ~ ~ hope that we can learn something ~. ~

Back to Table of contents-[Basic C + +-written assault] Overview

[Basic-C + + Foundation-surprise written test] 8. Class

Related Article

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.