C + + object oriented -- encapsulation

C + + object oriented encapsulation (1)

Date:2021.9.7
Author:lqy

  • 1, Three characteristics of object-oriented:

    Encapsulation, inheritance, polymorphism

  • 2, Object oriented design:

    Encapsulation:

    1. Class definition: member attribute, member method
    2. Instantiation of class object: create an object of class

    Requirements: define a circle class, define the member attribute of radius in the class, and define the member method to obtain the circumference of the circle

    // Define const constant - > const double pi = 3.14 outside the main() function;
    
    class Circle  // Class definition - class name
    {
    public:
        /*Member properties*/
    	int r;
    public:
        /*Member method*/
    	double calculator()
    	{
    		return 2 * pi * r;
    	}
    };
    
    void test01()
    {
    	Circle c;  // Class instantiation
    	/*Class names can be used to call member properties and member methods through "."*/
        c.r = 10;
    	cout << "The circumference of the circle is:" << c.calculator() << endl;
    }
    
  • 3, Access rights:

    • (1) public (2) protected (3) private
    • Permission level: private > protected > public
    • For the three permission member attributes, the method can be accessed within the class, the access outside the class can only access the public variable, and the access outside the protected and private classes cannot be accessed
    • The difference between protected and private is that when inheriting operations, subclasses can access variables with protected permission in the parent class, but subclasses cannot access variables with private permission
  • 4, Differences between struct and class:

    • Both struct and class can encapsulate objects
    • The default attribute of struct is public, and the default attribute of class is private
  • 5, Member property privatization

    During the actual development of C + + object-oriented, class member properties are generally set as private properties, and get and set methods are provided to access private properties

    advantage:

    1. Private attributes cannot be accessed directly outside the class to avoid misoperation of member attributes outside the class
    2. Filter operation can be set in get and set methods to ensure the validity of user input
    class Person
    {
    private:
        /*Person class Set private member property - Private*/
    	string name;
    	int age;
    public:
        /*Provide get and set methods to access private properties of members outside the class*/
    	string getName()
    	{
    		return name;
    	}
    	void setName(string T_name)
    	{
    		name = T_name;
    	}
    	int getAge()
    	{
    		return age;
    	}
    	void setAge(int T_age)
    	{
            /*set The filter mechanism is set inside the function to ensure the effectiveness of user input*/
    		if (T_age > 0 && T_age < 150)
    		{
    			age = T_age;
    		}
    		else
    		{
    			age = 0;
    			cout << "The age you entered is incorrect" << endl;
    		}
    	}
    };
    
    void test01()
    {
    	Person p;
    	p.setName("zhangsan");
    	p.setAge(20);
    	cout << "The name is:" << p.getName() <<","<< "Age is:" << p.getAge() << endl;
    }
    
  • 6, Class as a function parameter:

    Classes created object-oriented in C + + can also enter functions as function parameters for related operations

    /*In this example, the Person class uses the Person in the above example. In this example, it is not rewritten*/
    bool isSame(Person &p1,Person &p2)
        /*Pass in two Person objects by reference and call the member function of Person for function operation*/
    {
        if((p1.getName() == p2.getName())&&(p1.getAge() == p2.getAge()))
        {
            cout << "p1 and p2 identical" << endl;
        }else{
            cout << "p1 and p2 inequality" << endl;
        }
    }
    
  • 7, Class as a member property of the class:

    Requirement: design circle class, including center and radius

    Solution: design the point class and pass it into circle calcs as the center attribute of the circle class

    class Pointer
        /*Point class - > later passed into Circle class as Circle center*/
    {
    private:
        /*The horizontal and vertical (x,y coordinates) of the point are set to private properties*/
    	int x;
    	int y;
    public:
        /*Provide get and set methods for external public permissions to obtain horizontal and vertical coordinates*/
    	void setX(int T_x)
    	{
    		x = T_x;
    	}
    	int getX()
    	{
    		return x;
    	}
    	void setY(int T_y)
    	{
    		y = T_y;
    	}
    	int getY()
    	{
    		return y;
    	}
    };
    
    class Circle
    {
        /*Design circle class*/
    private:
    	int r;
    	Pointer p;   // Pass in class Pointer as a member property
    public:
    	void setR(int T_r)
    	{
    		r = T_r;
    	}
    	int getR()
    	{
    		return r;
    	}
        /*Provide get and set methods for class member properties*/
    	void setPointer(Pointer& T_p)  // An instantiated object of type Pointer is passed in by reference
    	{
    		p = T_p;
    	}
    	Pointer getPointer()          // The type of the returned object is user-defined data type - Pointer
    	{
    		return p;
    	}
    };
    
  • 8, Sub file writing of classes in C + +

    When using C + + to create a large project, multiple classes are written in the same code file, which has high maintenance cost and poor readability. In this case, using class sub file writing, you can create classes in other files to realize class sub file writing

    Steps:

    1. Add the. h header file and write the member properties of the class and the declaration of the member methods
    2. Add the. cpp file, write the concrete implementation of class member methods, and pay attention to the addition of function scope
    3. Add a header file in the main function file to create an instantiated object
    //Take the above Pointer as an example to demonstrate the sub file preparation of the class
    
    /*Add the. h header file and write the member properties of the class and the declaration of the member methods*/
    //Pointer.h file
    #pragma once / / prevent header files from being included repeatedly
    #include<iostream>
    using namespace std;
    
    class Pointer
    {
    	/*.h The file only needs to contain the declaration of member properties and member methods, and no specific implementation is required*/
    private:
    	int x;
    	int y;
    public:
    	/*The member method removes the function body and adds a semicolon after it*/
    	void setX(int T_x);
    	int getX();
    	void setY(int T_y);
    	int getY();
    };
    
    /*Add. cpp file and write the concrete implementation of class member methods*/
    //Pointer.cpp file
    #include "Pointer.h" / / include header file (note that double quotation marks are used instead of angle brackets)
    /*
    * 1. .cpp File to add a function specific implementation
    * 2. Function implementation increases the scope to ensure that it is used as a local function
    */
    
    void Pointer::setX(int T_x)
    {
    	x = T_x;
    }
    int Pointer::getX()
    {
    	return x;
    }
    void Pointer::setY(int T_y)
    {
    	y = T_y;
    }
    int Pointer::getY()
    {
    	return y;
    }
    
    /*Add a header file in the main function file to create an instantiated object*/
    //test.cpp file
    #include<iostream>
    using namespace std;
    #include "Pointer.h" / / include header file (note that double quotation marks are used instead of angle brackets)
    
    void test01()
    {
        Pointer p;
    }
    
    
  • 9, Object initialization and cleanup in C + +

    1. The initialization and cleaning of objects in C + + are completed with the help of constructors and destructors
    2. Programmers do not provide constructors and destructors. The compiler will provide them automatically, but the constructors and destructors provided by the compiler are empty implementations
    3. If the programmer manually provides constructors and destructors, the compiler will not provide default constructors and destructors

    Constructor and destructor syntax:

    Constructor - > class name () {} (constructor will be called when creating instantiated object of class)

    Destructor - > ~ class name () {} (the call time of destructor is called when the instantiated object is destroyed. The data program opened on the stack is destroyed when it exits. The data opened in the heap area needs the programmer to manually manage life and death, so the object is destroyed when the programmer delete s the object)

    Tips:

    1. Constructors and destructors have no return value and do not write void
    2. The function name must be the same as the class name
    3. The program will automatically call the constructor and destructor without manual call, and will only call it once
    4. Constructors can have parameters, that is, function overloading occurs, while destructors cannot have function overloading, that is, destructors cannot have parameters
    #include<iostream>
    using namespace std;
    
    class Person
    {
    public:
    	/*Nonparametric construction and parameterized constructor*/
    	Person() {}
    	Person(string name, int age)
    	{
            /*this Pointer to the created object*/
    		this->name = name;
    		this->age = age;
    	}
    	/*Destructor*/
    	~Person() {}
    private:
    	string name;
    	int age;
    };
    
    void test01()
    {
        /*Execute the test01() function, and the Person constructor and destructor will be called*/
    	/*Person The object is opened in the stack area, and the object is released after the test01() function call is completed*/
    	Person p;
    }
    
    int main()
    {
        /*Execute the main() function. At this time, only the constructor of Person will be called, not the destructor*/
        /*Because the main() function contains the system("pause") code, the program will stop at this position. If you press any key, the program will exit, the Person object will be released, and the destructor will be called*/
        Person p1;
        
        system("pause");
        return 0;
    }
    
  • 10, Constructor in C + +

    • Classified by parameters: parametric structure and nonparametric structure

      /*Parameterized and nonparametric constructors*/	
      Person() {}
      Person(string name,int age)
      {
          this->name = name;
          this->age = age;
      }
      
    • Classification by type: normal construction and copy construction

      //The above parameterized and nonparametric constructors are ordinary constructors
      Person(const Person& p)
      {
      /*Copy constructor - > 1. The parameter is a person object of the same class. 2. Person is modified by const to prevent accidental modification. 3. Person is passed by reference*/
      this->name = p.name;
      this->age = p.age;
      }
      
    • Constructor call method:

      1. bracketing

        Person p("liqiyan",11);
        
      2. Display method

      3. Implicit transformation method

    • Anonymous objects in C + +:

      Initializing anonymous objects using bracket method

      Person("liqiyan",10);
      
  • 11, Constructor call timing in C + +

    • The created object initializes another new object

    • The value transfer method is to transfer values to function parameters

      void doWork(Person p)
      /*Value passing copies temporary copies without affecting the original value*/
      {}
      
      void test02()
      {
      	Person p;  
      	doWork(p);
          /*At this time, p itself is not passed as a function parameter, but a new sample copy copied from the p object*/
      }
      
    • Returns a local object as a value

      Person doWork2()
      {
      	Person p1;
      	return p1;
          /*What is returned here is not the p1 object itself, but a copy copied according to the copy constructor*/
      }
      
  • 12, Constructor call rule:

    • Default functions of C + + classes:
      1. Default constructor (no parameters, empty function body)
      2. Default destructor (no parameters, empty function body)
      3. Copy constructor (value copy)
    • C + + default function call rules:
      1. Add a parameter constructor by yourself. C + + does not provide a default constructor, but still provides a copy constructor
      2. Add a copy constructor by yourself. C + + will not provide default constructs and parametric constructs

Keywords: C++

Added by IsmAvatar on Sat, 02 Oct 2021 00:51:50 +0300