C ++ class learning special functions and this pointer

1. Constructor

  A constructor is a special function that is called when the object is created with the same name as the class no return type, can be overloaded. May be implemented outside the class may also be implemented in the class constructor.

  Statement constructor code similar to the following:

class Human 
{ 
 public : 
    Human (); // constructor declaration 
};

  Constructor implemented in code similar to the following class declaration:

class Human 
{ 
public : 
    Human () 
    { 
        // achieve some constructor 
    } 
};

  Constructor implemented similar to the following code outside the class declaration:

class Human 
{ 
public : 
    Human (); 
}; 
Human :: Human () 
{ 
     // achieve some constructor 
};

  Allow us to use a constructor to initialize attributes within the class, known attributes to ensure that does not contain a random value. Constructors also be overloaded, indicating that the constructor is sometimes necessary to provide parameters when calling the constructor, you can call in case of no argument

Known as the default constructor. When calling the constructor to initialize the object attributes, but also need to provide different parameters, then the overloaded constructor that we can help.

  Overloaded constructor code similar to the following:

class Human
{
private:
    string Name;
    int Age;
public:
    Human (int HumanAge)
    {
       Age=HuanAge; 
    }
    Human (string HumanName,int HumanAge)
    {
        Name=HumanName;
        Age=HumanAge;
    }
};

  In fact, not only can be overloaded constructor whose parameters can also comes with a default value.

  Such as the following:

class Human 
{ 
Private :
     String the Name;
     int Age;
 public : 
    Human ( int HumanAge) 
    { 
       Age = HuanAge; 
    } 
    Human ( String the HumanName, int HumanAge = 22 is ) // differ on a piece of code that is given a default value HumanAge 
    { 
        the Name = the HumanName; 
        Age = HumanAge; 
    } 
   
   / *Human (int HumanAge, string HumanName = "Tom") // symbols removed from the multi-line comments, this overload being given, because when a parameter of type int calling the constructor, the system does not know the call Human ( int) Human (int, the HumanName String = "Tom") 
    { 
        the Name = the HumanName; 
        Age = HumanAge; 
    } * / 
};

 

2. destructor

  And destructor, destructor looks the same name and category, but more in front of the function name tilde "~." Whenever an object is deleted by delete or no longer in scope, and then will call the destructor is destroyed. This makes variable destructor is reset and the release of memory and other resources over the place dynamically allocated. The destructor can not be overloaded Each class can have a destructor, if forget to implement destructor, the system automatically generates a pseudo destructor, since the pseudo destructor is empty it can not release the memory space allocated dynamically .

  The class destructor achieve similar to the following code:

class Human 
{ 
 public :
     ~ Human () 
   { 
       // destructor achieve some 
   } 

};

  Class destructor outer achieve similar to the following code:

class Human 
{ 
 public :
     ~ Human (); 
}; 
Human :: Human () 
{ 
  // destructor achieve some 
};

  When the function where the object has been invoked completed, the system automatically performs the destructor; with the new opened up a memory space, delete automatically calls the destructor after the release of memory; the object A is a member object B, destructors B is called , the destructor of the object a will be invoked.

3. Copy Constructor

  3.1 shallow copy its problems:

    When members of a class contains a pointer, an object class definition has as arguments to a function of the parameter (i.e., replication), a member of the pointer will be copied. Pointer Pointer members and members of the copied original objects point to the same memory space, which is called a shallow copy, threaten the stability of the program.

  For example, the following program is problematic:

#include<iostream>
#include<cstring> 
using namespace std;
void strcpy_s(char* pre, const char* next)
{
    if (next != NULL)
    {
        while ((*pre++ = *next++) != '\0');
    }
}
class MyString
{
private:
    char* Buffer;
public:
    MyString(const char *InitialInput)
    {
        if(! InitialInput = NULL) 
        { 
            Buffer = new new  char [strlen (InitialInput) + . 1 ]; // Buffer space allocated to the new 
            strcpy_s (Buffer, InitialInput); 
        } 
        the else  
            Buffer = NULL; 
    }
     ~ MyString () 
    { 
        IF (Buffer ! = NULL) 
        { 
            COUT << " destructor, release the memory " << endl;
             IF ! (Buffer = NULL)
                 Delete  [] Buffer;
        } 
    }
    int a GetLength () 
    { 
        return strlen (Buffer); 
    } 
    const  char * the GetString () 
    { 
        return Buffer; 
    } 
}; 
void UseMyString (MyString Input) // argument object will be copied to the Input parameter when invoked 
{ 
    COUT < < " Buffer word Count: " << Input.GetLength (); 
    COUT << " Buffer content: " << Input.GetString ();
     return ; 
} 
int main ()  
{
    MyString the SayHello ( " the Hello");
    UseMyString(SayHello);
    return 0;
}

 

  UseMyString when calling the function, the argument is shallow copy SayHello parameter to Input. In the process of passing parameters, SayHello has had a member pointer Buffer, SayHello.Buffer will address to the Input.Buffer (transfer mode parameters of this function like they); this will cause them to point to the same piece of memory space . When the call is completed UseMyString function will call the destructor release Inpu memory space, and then return to the main function, when the main function is to perform complete will call the destructor frees SayHello memory space, then problems will arise, and because Input.Buffer SayHello.Buffer point to the same memory space at this time but is continuously performed twice destructor releases the same memory space (the program will not return to normal or crash).

  The biggest problem is the existing shallow copy will be possible to replicate the object and the original object shared phenomenon of a block of memory, this is likely to share memory problems when released. We will be introducing copy constructor deep copy solve similar problems.

  3.2 using the copy constructor:

    The copy constructor is a special overloaded constructor, we must provide it when you use the class. Whenever an object is copied when including the object as a parameter to the function by value, the compiler will call the copy constructor. Copy constructor takes a subject of the current class of reference passed as a parameter. This parameter is an alias of the source object, we use it in the constructor to copy source object, make sure to copy all buffers.

    The above modifications are given below shallow copy deep copy of the code is:

 

#include<iostream>
#include<cstring>
using namespace std;
void strcpy_s(char* pre, const char* next)
{
    if (next != NULL)
    {
        while ((*pre++ = *next++) != '\0');
    }
}
class MyString
{
private:
    char* Buffer;
public:
    MyString(const char* InitialInput)
    {
        if(! InitialInput = NULL) 
        { 
            Buffer = new new  char [strlen (InitialInput) + . 1 ]; 
            strcpy_s (Buffer, InitialInput); 
        } 
        the else  
            Buffer = NULL; 
    } 
    MyString ( const MyString & copysource) // copy constructor 
    { 
        COUT << " object copy from the source: " << endl;
         IF (! CopySource.Buffer = NULL) 
        { 
            Buffer = new new  char[strlen(CopySource.Buffer) + 1];
            strcpy_s(Buffer, CopySource.Buffer);
        }
        else
            Buffer = NULL;
    }
    ~MyString()
    {
        if(Buffer!=NULL)
        { 
            cout << "析构,释放内存" << endl;
            if (Buffer != NULL)
                delete[] Buffer;
        }
    }
    int GetLength()
    {
        return strlen(Buffer);
    }
    const char* GetString()
    {
        return Buffer;
    }
};
void UseMyString(MyString Input)
{
    cout << "Buffer 字数为:" << Input.GetLength()<<endl;
    cout << "Buffer 内容为:" << Input.GetString()<<endl;
    return;
}
int main()
{
    MyString SayHello("Hello");
    UseMyString(SayHello);
    return 0;
}

 

4.this pointer

  In C ++, an important concept of this keyword is reserved, in the class, this keyword contains the current address of the object, in other words, a value of & object. When you call the other members of the methods in the class member method, the compiler would implicitly transfer this pointer - function call invisible parameters:

 

#include<iostream>
#include<cstring>
using namespace std;
class Human
{
private:
    int Age;
    char Name;
public:
    void SetAge(int HumansAge)
    {
        Age = HumansAge;//修改当前对象的Age值
   cout<<Age;
    }
};
int main()
{
    Human FirstMan;
    FirstMan.SetAge(21);
    return 0;
}  

 

  When the above call class objects Firstman static function will exist implicitly passed the this pointer, i.e. calling FirstMan (21) corresponds to the equivalent FirstMan (this, 21); Access to the object member Age corresponds this-> Age = HumanAge. Throughout the course of this points to the current object, it stores the current address of the object.

 Attached : a classic pointer on this answer:
  When you enter a house,
  You can see tables, chairs, floors,
  But the house you can not see the whole picture.
  For instance of a class, the
  You can see it's member functions, member variables,
  But the example itself?
  this is a pointer, it always points you in this instance itself.

 

 

  

 

  

 

  

Guess you like

Origin www.cnblogs.com/dulm/p/11249506.html