Home > Backend Development > C#.Net Tutorial > C++ learning basic knowledge--this pointer, static members, constant member functions

C++ learning basic knowledge--this pointer, static members, constant member functions

php是最好的语言
Release: 2018-08-08 11:29:50
Original
2005 people have browsed it

1. this pointer

1. Translation from C program to C program

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;                         }
}
Copy after login

2. Function of this pointer: This can be used directly in non-static member functions to represent the pointer Pointer to the object that this function acts on

3, this pointer and static member function: Static member function does not specifically act on a certain object, so the this pointer cannot be used in static member function

2 , Static members

  • Static members: members with the static keyword in front of the description.

  • Ordinary member variables have their own copy for each object, while static member variables only have one copy in total, which is shared by all objects. The sizeof operator will not calculate static member variables.

  • Ordinary member functions must specifically act on an object, while static member functions do not specifically act on an object and can be accessed without passing the object.

class CRectangle{
    private:
        int w, h;
        static int nTotalArea; // 静态成员变量
    public:
        CRectangle(int w_,int h_);
        ~CRectangle();
        static void PrintTotal(); // 静态成员函数
};
Copy after login

1. Method to access static members:

  • Class name::Member name CRectangle::PrintTotal();

  • Object name.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. Notes:

  • Static member variables are essentially global variables. Even if an object does not exist, the static member variables of the class still exist

  • must be defined The static member variables are described or initialized once in the class file. Otherwise, the compilation can pass, but the linking cannot.

  • In a static member function, non-static member variables cannot be accessed, and non-static member functions cannot be called

3. Member objects and enclosed classes

1. Definition: A class with member objects is called an enclosing class

class CTyre{             // 轮胎类
    private:
        int radius;      // 半径
        int width;       // 宽度
    public:
        CTyre(int r,int w):radius(r),width(w) { }
};
class CEngine{           // 引擎类
};
class CCar {             // 汽车类
    private:
        int 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;
}
Copy after login

In the above example, if the CCar class does not define a constructor, then The following statement will cause a compilation error: CCar car; because the compiler does not understand how car.tyre should be initialized. There is no problem with the initialization of car.engine, just use the default constructor. Any statement that generates a closed class object must let the compiler understand how the member objects in the object are initialized. The specific method is: through the initialization list of the constructor of the closed class.

2. Execution order of closed class constructors and destructors

  • When a closed class object is generated, the constructors of all object members are executed first, and then the closure is executed. Class constructor.

  • The constructor calling order of object members is consistent with the order in which the object members are described in the class, regardless of the order in which they appear in the member initialization list.

  • When the object of the closed class dies, the destructor of the closed class is executed first, and then the destructor of the member object is executed. The order is the opposite of the calling order of the constructor.

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;
}
//输出结果:
CEngine contructor
CTyre contructor
CCar contructor
CCar destructor
CTyre destructor
CEngine destructor
Copy after login

4. Friends

1. Friends are divided into two types: friend function and friend class

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

class CCar ;     //提前声明 CCar 类,以便后面的CDriver 类使用
class CDriver{
    public:
    void ModifyCar( CCar * pCar) ;         // 改装汽车
};
class CCar{
    private:
        int price;
        friend int MostExpensiveCar( CCar cars[], int total); // 声明友元
        friend void CDriver::ModifyCar(CCar * pCar);     // 声明友元,可包括构造、析构函数
};
void CDriver::ModifyCar( CCar * pCar){
    pCar->price += 1000;                        // 汽车改装后价值增加
}
int MostExpensiveCar( CCar cars[],int total){   // 求最贵汽车的价格                           
    int tmpMax = -1;
    for( int i = 0;i < total; ++i )
    if( cars[i].price > tmpMax)
    tmpMax = cars[i].price;
    return tmpMax;
}
Copy after login

(2) Friend class: If A is a friend class of B, then the member functions of A can access the private members of B The relationship between members and friend classes cannot be transferred or inherited

class B{
    friend class A;      // 声明A为友元类
};
Copy after login

5. Constant member function

1. Function: If you do not want the value of an object to be changed, define the When using an object, you can add the const keyword

  • in front of the object. You can add the const keyword after the member function description of the class, and the member function becomes a constant member function.

  • The value of the attribute cannot be changed inside the constant member function, nor can the non-const member function be called.

  • When defining the constant member function and declaring the constant member The const keyword should be used in all functions

class Sample {
    private :
        int value;
    public:
        Sample() { }
        void SetValue() {  }
};
const Sample Obj;  //  常量对象
Obj.SetValue ();   //错误,常量对象只能使用构造函数、析构函数和有const说明的函数(常量方法)
Copy after login

2. Overloading of constant member functions: two functions have the same name and parameter list, but one is const and the other is not. Overloading

3. Mutable member variables:

(1) Function: mutable is set beyond the constraints of const. Variables modified by mutable will always be in a variable state, even in a in const function.

(2) Application: If the member function of the class does not change the state of the object, it will generally be declared as const. However, sometimes, it is necessary to modify some data members that have nothing to do with the class state in a const function, then these data members should be modified with mutable.

class CTest{
    public:
        bool GetData() const{
            m_n1++;
            return m_b2;
        }
    private:
        mutable int m_n1;
        bool m_b2;
};
Copy after login

Related recommendations:

C The use of static members and constant members

C Summary of review points 5 Static member variables and members function

The above is the detailed content of C++ learning basic knowledge--this pointer, static members, constant member functions. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template