C + + Learning basics--this pointers, static members, constant member functions

Source: Internet
Author: User
First, this pointer





1. C + + program to C program translation


class CCar {                          struct CCar {

    public:                                int price;

    int price;                        };

    void SetPrice(int p);             void SetPrice(struct CCar * this,int p){

};                                        this->price = p;

void CCar::SetPrice(int p){           }

    price = p; //this->price = p;

}                                     int main() {

int main(){                               struct CCar car;

    CCar car;                             SetPrice( & car,20000);

    car.SetPrice(20000);                  return 0;

    return 0;                         }

}


2, this pointer action: non-static member function can use this directly to represent the object to the function of the pointer



3. This pointer and static member function: Static member functions do not specifically work with an object, so the this pointer cannot be used in a static member function



Second, static members


    • Static member: the member that added the static keyword before the description.

    • Ordinary member variables each object has its own copy, and the static member variable is one copy, shared for all objects, and the sizeof operator does not evaluate static member variables.

    • Ordinary member functions must be specific to an object, and static member functions do not specifically work on an object and are not accessible through an object.

Class CRectangle{

     Private:

         Int w, h;

         Static int nTotalArea; // static member variable

     Public:

         CRectangle(int w_, int h_);

         ~CRectangle();

         Static void PrintTotal(); // static member function

};


1. Methods to access static members:


    • Class Name:: member name Crectangle::P rinttotal ();

    • The name of the object. Member name Crectangle R; R.printtotal ();

    • Pointer--member name Crectangle * p = &r; P->printtotal ();

    • Reference. Member name Crectangle & ref = R; int n = ref.ntotalnumber;


2. Precautions:


    • A static member variable is essentially a global variable, and even if an object does not exist, the static member variable of the class exists

    • Static member variables must be described or initialized once in the file that defines the class. Otherwise the compilation can pass, the link cannot pass

    • In a static member function, you cannot access a non-static member variable, or you cannot call a non-static member function


Iii. member objects and enclosing classes



1. Definition: Class with member object called enclosing (enclosing) class


Class CTyre{ // Tires

     Private:

         Int radius; // radius

         Int width; // width

     Public:

         CTyre(int r, int w):radius(r),width(w) { }

};

Class CEngine{ // engine class

};

Class CCar { // Automotive

     Private:

         Int price; // price

         CTyre tyre;

         CEngine engine;

     Public:

         CCar(int p, int tr, int tw );

};

CCar::CCar(int p,int tr,int w):price(p),tyre(tr, w){};

Int main(){

     CCar car (20000, 17, 225);

     Return 0;

}

In the above example, if the Ccar class does not define a constructor, the following statement compiles an error: Ccar car, because the compiler does not understand how Car.tyre is initialized. The initialization of the car.engine is no problem, with the default constructor. Any statement that generates an enclosing class object will let the compiler understand how the member object in the object is initialized. The specific approach is to initialize the list by enclosing the constructor of the class.



2. Execution order of enclosing class constructors and destructors


    • When the enclosing class object is built, the constructors for all object members are executed before the enclosing class is executed.

    • The order of constructor calls for object members and the order in which object members are described in the class are not related to the order in which they appear in the member initialization list.

    • When an object of the enclosing class dies, the destructor for the enclosing class is executed before the destructor for the member object is executed. The order and constructor are called in reverse order.

Class CTyre {

     Public:

         CTyre() { cout << "CTyre contructor" << endl; }

         ~CTyre() { cout << "CTyre destructor" << endl; }

};

Class CEngine {

     Public:

         CEngine() { cout << "CEngine contructor" << endl; }

         ~CEngine() { cout << "CEngine destructor" << endl; }

};

Class CCar {

     Private:

         CEngine engine;

         CTyre tyre;

     Public:

         CCar( ) { cout << “CCar contructor” << endl; }

         ~CCar() { cout << "CCar destructor" << endl; }

};

Int main(){

     CCar car;

     Return 0;

}

/ / Output results:

CEngine contructor

CTyre contructor

CCar contructor

CCar destructor

CTyre destructor

CEngine destructor


Four, friend Yuan (friends)



1, friend is divided into friend function and friend class two kinds



(1) Friend function: A friend function of a class can access the private members of the class


Class CCar ; //Declare the CCar class in advance so that it can be used by the CDriver class later

Class CDriver{

     Public:

     Void ModifyCar( CCar * pCar) ; // modified car

};

Class CCar{

     Private:

         Int price;

         Friend int MostExpensiveCar( CCar cars[], int total); // Declare friends

         Friend void CDriver::ModifyCar(CCar * pCar); // Declare friends, including constructors, destructors

};

Void CDriver::ModifyCar( CCar * pCar){

     pCar->price += 1000; // Increased value after car modification

}

Int MostExpensiveCar( CCar cars[],int total){ // Ask for the price of the most expensive car

     Int tmpMax = -1;

     For( int i = 0;i < total; ++i )

     If( cars[i].price > tmpMax)

     tmpMax = cars[i].price;

     Return tmpMax;

}


(2) Friend class: If A is a friend of B, then the member function of a can access the private member of B, the relationship between the friend class cannot be passed, and cannot inherit


Class b{    friend class A;      Statement A is a friend class};


Five, constant member functions



1. Function: If you do not want the value of an object to be changed, you can add the Const keyword in front of the object when you define it


    • This member function becomes a constant member function when you can add the Const keyword after the member function description of the class.

    • The value of a property cannot be changed inside a constant member function, nor can it be called a const member function

    • You should use the Const keyword when defining a constant member function and declaring a constant member function

Class Sample {

     Private :

         Int value;

     Public:

         Sample() { }

         Void SetValue() { }

};

Const Sample Obj; // constant object

Obj.SetValue (); / / error, constant object can only use constructors, destructors and functions with const description (constant method)


2, the overload of the constant member function: Two functions, the name and parameter table are the same, but one is a const, one is not, calculate the overload



3. mutable member variables:



(1) Function: mutable break through the limitations of the const set, the variable modified by mutable will always be in a mutable state, even in a const function.



(2) Apply: If the member function of a class does not change the state of the object, it is generally declared as Const. However, there are times when you need to modify some data members that are unrelated to the class state in a const function, then the data members should be mutable.



class CTest{

    public:

        bool GetData() const{

            m_n1++;

            return m_b2;

        }

    private:

        mutable int m_n1;

        bool m_b2;

};



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.