C + + foundation-4-encapsulation (constructor and destructor, deep copy and shallow copy, static member, this, friend, const, modified member function)

Time:2022-5-9

4. Packaging

4.1.1 significance of packaging

1 #include
  2 #include
  3 using namespace std;
  4 
  5 const double PI = 3.14;
  6 
  7 // design a circle class to find the circumference of the circle
  8 // perimeter formula: 2 * pi * radius
  9 
 10 class Circle {
 11 // public permission
 12 public:
 13 // properties
 14     int m_r;
 15 
 16 // behavior, generally function
 17     double calZC() {
 18         return 2 * PI * m_r;
 19     }
 20 
 21 };
 22 
 23 // design a student class with the attributes of student ID and name;
 24 // assign a value to the student's name and student number, and display the student number and name
 25 
 26 class Student {
 27 public:
 28     string m_Name;
 29     int m_ID;
 30 
 31     void showStu() {
 32 cout < < Student Name: < < m_ Name < < student No.: < < m_ ID << endl;
 33 
 34     }
 35 
 36     void setName(string name) {
 37         m_Name = name;
 38     }
 39 
 40     void setID(int id) {
 41         m_ID = id;
 42     }
 43 
 44 };
 45 
 46 
 47 class Person {
 48 public: // public permission, which can be accessed by all internal classes
 49     string m_Name;
 50 
 51 protected: // protect permissions, which can be accessed within the class but not outside the class
 52     string m_Car;
 53 
 54 private: // private permission. It can be accessed within the class, but not outside the class
 55     int password;
 56 
 57 /// 
 58 // in inheritance, children with protected permissions can access, but children with private permissions cannot access;
 59 /// 
 60 public:
 61     void func() {
 62         m_ Name = "Zhang San";
 63         m_ Car = "Benz";
 64         password = 123;
 65     }
 66 };
 67 
 68 
 69 int main() {
 70 
 71 // create a specific circle (object) through the circle class
 72     //Circle cl;
 73     //cl.m_r = 10;
 74 // cout < "the circumference of the circle is:" < cl.calzc() < < endl;
 75 
 76     //Student stu1;
 77     ////stu1. m_ Name = "Xiao Ming";
 78     //stu1. Setname ("Xiao Ming");
 79     ////stu1.m_ID = 123123;
 80     //stu1.setID(123321);
 81     //stu1.showStu();
 82 
 83     //Student stu2;
 84     //stu2. m_ Name = "Zhang San";
 85     //stu2.m_ID = 2222;
 86     //stu2.showStu();
 87 
 88     Person p1;
 89     p1.func();
 90 cout < < the name of person 1 is: < < P1 m_ Name << endl;
 91 
 92 
 93 
 94     system("pause");
 95 
 96     return 0;
 97 }
 98 
 99 // summary
100 // understand the creation and three permissions of class;
101 // distinguish between class and struct:
102 // the default access permissions are different. The default permissions of struct and class are public and private respectively
103 //

 

4.1.2 privatization of member attributes

1 #include
 2 using namespace std;
 3 #include
 4 
 5 // privatization of member attributes
 6 //1. Control the read and write permissions by yourself
 7 //2. Validity of test data
 8 
 9 class Person {
10 public:
11 // write your name
12     void setName(string name) {
13         m_Name = name;
14     }
15 // get name
16     string getName() {
17         return m_Name;
18     }
19 
20 // get age
21     int getAge() {
22         //m_Age = 10;
23         return m_Age;
24     }
25 
26     void setAge(int age) {
27         if (age < 0 || age > 150) {
28             m_Age = 0;
29 cout < < "wrong age setting!"<< endl;
30             return;
31         }
32         m_Age = age;
33     }
34 
35 
36 private:
37     string m_ Name; // Readable and writable
38     int m_ Age;  // readable
39 
40 };
41 
42 
43 int main() {
44 
45     Person p1;
46     p1. Setname ("Zhang San");
47     cout << p1.getName() << endl;
48 
49     p1.setAge(1000);
50     cout << p1.getAge() << endl;
51 
52     p1.setAge(15);
53     cout << p1.getAge() << endl;
54 
55     system("pause");
56 
57     return 0;
58 }
59 
60 // summary
61 // privatize the member properties, and you can control the read and write permissions yourself
62 // for write permission, you can check the validity of the data

 

4.2.1 constructors and destructors

1 #include
 2 using namespace std;
 3 
 4 // object initialization and cleanup
 5 class Person {
 6 public:
 7 // constructor
 8     Person() {
 9 cout < < "constructor of person!"<< endl;
10     }
11 
12 // destructor
13     ~Person() {
14 cout < < "destructor of person!"<< endl;
15     }
16 
17 };
18 
19 
20 void test01() {
21     Person p1; // Local variable, in the stack area, release this object after test01 is executed;
22 }
23 
24 
25 int main() {
26 
27     test01();
28 
29     system("pause");
30 
31     return 0;
32 }
33 
34 // summary
35 // constructor:
36 // function: initialization, member attribute assignment
37 // syntax: class name () {}
38 // no value is returned and void is not written
39 // there can be parameters and overloading can occur
40 // it is called automatically without manual adjustment. It is only adjusted once
41 // 
42 // destructor:
43 // function: clear to zero. Before the object is destroyed, the system will automatically call to clean it up
44 // syntax: ~ class name () {}
45 // no parameters, no function overloading
46 // it is called automatically without manual adjustment. It is only adjusted once
47 //
48 // constructors and destructors are mandatory implementations. If we don't write them, the compiler will automatically provide the construction and destructor of empty implementations

 

4.2.2 classification and calling of constructors

1 #include
 2 using namespace std;
 3 
 4 class Person {
 5 public:
 6     Person() {
 7 cout < < "person's parameterless constructor (default constructor)!"<< endl;
 8     }
 9 
10     Person(int a) {
11         age = a;
12 cout < < "person's parameterized constructor!"<< endl;
13     }
14 
15 // copy constructor (remember how to write it!)
16     Person(const Person &p) {
17 // copy all the passed in attributes to the current;
18         age = p.age;
19 cout < < "copy constructor of person!"<< endl;
20     }
21 
22 
23     ~Person() {
24 cout < < "destructor of person!"<< endl;
25     }
26 
27     int age;
28 };
29 
30 // call
31 void test01() {
32     //1. bracketing
33 
34     //Person p1; //  Default constructor function of percon, without ()
35     //Person p2(10); //  Parametric structure
36     //Person p3(p2); //  copy construction 
37 
38 // // Note:
39 // // when calling the default constructor, do not add ()
40 // cout < < the age of P2 is: < < P2 age << endl;
41 // cout < < the age of P3 is: < < P3 age << endl;
42 
43 
44     //2. Display method
45     //Person p1;
46     //Person p2 = Person(10);  // Parametric structure
47     //Person p3 = Person(p2);  // copy construction 
48 
49     //Person(10); // Anonymous object features: after the execution of the current line, the system will immediately recycle the anonymous object;
50 // // Note:
51 // // do not use the copy constructor to initialize anonymous objects. The compiler will think this is a declaration;
52     ////Person(p3);  // report errors
53 
54     //3. Implicit transformation method
55 
56     Person p4 = 10; // Equivalent to person P4 = person (10);
57     Person p5 = p4; //  copy construction 
58 
59 
60 }
61 
62 
63 int main() {
64 
65     test01();
66 
67     system("pause");
68 
69     return 0;
70 }
71 
72 // summary
73 // classification: with / without reference; Normal / copy
74 // call: bracket method / display method / hermit conversion method
75 //
76 //

 

4.2.3 call timing of copy constructor

1 #include
 2 using namespace std;
 3 
 4 class Person {
 5 public:
 6     Person() {
 7 cout < < "person's parameterless constructor!"<< endl;
 8     }
 9 
10     Person(int a) {
11         m_Age = a;
12 cout < < "person's parameterized constructor!"<< endl;
13     }
14 
15     Person(const Person& p) {
16         m_Age = p.m_Age;
17 cout < < "copy constructor of person!"<< endl;
18     }
19 
20     ~Person() {
21 cout < < "destructor of person!"<< endl;
22     }
23 
24     int m_Age;
25 
26 };
27 
28 // 1. Initializes a new object using the object that has already been created
29 void test01() {
30     Person p1(20);
31     Person p2(p1);
32 cout < < the age of P2 is: < < P2 m_ Age << endl;
33 }
34 
35 //2. Value is passed to function parameters
36 void doWork(Person p) {
37 
38 }
39 
40 void test02() {
41     Person p;
42     doWork(p);
43 }
44 
45 //3. Returns a local object as a value, which returns a new object
46 
47 Person doWork2() {
48     Person p1;
49     return p1;
50 }
51 
52 void test03() {
53     Person p = doWork2();
54 }
55 
56 int main() {
57 
58     //test01();
59     //test02();
60     test03();
61 
62     system("pause");
63 
64     return 0;
65 }
66 
67 
68 // summary
69 // 1. Initializes a new object using the object that has already been created
70 // 2. Value is passed to function parameters
71 // 3. Returns a local object as a value
72 //

 

4.2.4 calling rules of constructor

1 #include
 2 using namespace std;
 3 
 4 class Person {
 5 public:
 6     Person() {
 7 cout < < "person's parameterless constructor!"<< endl;
 8     }
 9 
10     Person(int a) {
11         m_Age = a;
12 cout < < "person's parameterized constructor!"<< endl;
13     }
14 
15     Person(const Person& p) {
16         m_Age = p.m_Age;
17 cout < < "copy constructor of person!"<< endl;
18     }
19 
20     ~Person() {
21 cout < < "destructor of person!"<< endl;
22     }
23 
24     int m_Age;
25 
26 };
27 
28 void test01() {
29     Person p1;
30     p1.m_Age = 18;
31 
32     Person p2(p1);
33 cout < < the age of P2 is: < < P2 m_ Age << endl;
34 
35 
36 }
37 
38 int main() {
39 
40     test01();
41 
42     system("pause");
43 
44     return 0;
45 }
46 
47 // summary
48 // C + + adds three functions to a class by default:
49 // default constructor / default destructor / default copy constructor
50 //

 

4.2.5 deep copy and shallow copy

1 #include
 2 using namespace std;
 3 
 4 class Person {
 5 public:
 6     Person() {
 7 cout < < "person's parameterless constructor!"<< endl;
 8     }
 9 
10     Person(int age, int height) {
11         m_Age = age;
12         m_ Height = new int(height);  // Create heap data
13 
14 cout < < "person's parameterized constructor!"<< endl;
15     }
16 
17 // there is a reference constructor, which is implemented by initializing the list
18     Person(int age, int num): m_Age(age), m_Num(num)
19     {
20         //m_Age = age;
21         //m_ Height = new int(height);  // Create heap data
22 
23 cout < < "person's parameterized constructor!"<< endl;
24     }
25 
26 
27     Person(const Person& p) {
28         m_Age = p.m_Age;
29         //m_ Height = p.m_ Height; // The compiler implements this line of code by default
30 // this line of code is a shallow copy, which will cause the heap memory to be released repeatedly, and the program reports an error
31 
32 // use deep copy to solve the problem and reopen the heap space
33         m_Height = new int(*p.m_Height);
34 
35 cout < < "copy constructor of person!"<< endl;
36     }
37 
38     ~Person() {
39 // destruct the code and release the data in the heap area;
40         if (m_Height != NULL)
41         {
42             delete m_Height;
43             m_Height = NULL;
44         }
45 
46 // problems caused by shallow copy: repeated release of heap data,
47 // use the deep copy method to solve the problem
48 
49 
50 cout < < "destructor of person!"<< endl;
51     }
52 
53     int m_Age;
54     int m_Num;
55     int *m_Height;
56 };
57 
58 void test01() {
59 
60     Person p1(18, 160);
61 cout < < P1's age is: < < P1 m_ Age << endl;
62 cout < < P1's height is: < < * P1 m_ Height << endl;
63 
64     Person p2(p1);
65 
66 cout < < the age of P2 is: < < P2 m_ Age << endl;
67 cout < < P2's height is: < < * P2 m_ Height << endl;
68 
69 }
70 
71 int main() {
72 
73     test01();
74 
75     system("pause");
76 
77     return 0;
78 }
79 
80 
81 // summary
82 // shallow copy: simple assignment copy operation
83 // deep copy: reapply space in the heap area and copy
84 // if the attribute is opened in the heap area, you must provide your own copy constructor to prevent problems caused by shallow copy
85 //
86 // other conclusions
87 // when other class objects are members of this class. Constructors first construct objects and then construct themselves. The order of deconstruction is opposite to that of construction
88 //

 

4.2.6 static members

#include
using namespace std;

class Person {
public:
    
    static int a; // Static member variable, declared in class
    int b; // Non static member variable
    static void func()
    {
        a = 100; // Static member functions can access static member variables, which are shared
        Cout < < static member function < < endl;
        Cout < < the value of static member variable a is: < < a < < endl;
        //b = 200; // An error is reported. Static member functions cannot access non static member variables; It is impossible to distinguish which object is B
    }

    //Static member functions also have access rights
private:
    static void func1() {
        Cout < < private static member function < < endl;
    }

};

int Person::a = 10; // Out of class initialization

void test01() {
    //1. Access by object
    Person p;
    p.func();

    //2. Access by class name
    Person::func();

}

int main() {

    test01();

    system("pause");

    return 0;
}


//Summary
//The static keyword is added to member attributes and member functions to become static members
// 
//Static members:
// 1. All objects share the same data
// 2. Allocate memory at compile time
// 3. In class declaration, out of class initialization
// 
//Static member function:
// 1. All objects share the same function
// 2. Static member functions can only access static member variables (redo)
// 
//

 

4.3.1 member variables and member functions are stored separately

1 #include
 2 using namespace std;
 3 
 4 // member variables and member functions in the class are stored separately
 5 
 6 class Person {
 7     int m_ A; // Non member variables on static objects
 8     static int m_ B;  // Static member variable, on an object that does not belong to a class
 9 
10 void func() {// a non static member function on an object that does not belong to a class
11 
12     }
13 static void func2() {// a static member function on an object that does not belong to a class
14 
15     }
16 
17 };
18 
19 int Person::m_B = 0;
20 
21 
22 void test01() {
23     Person p;
24 // the memory space occupied by an empty object is: 1
25 // the C + + compiler allocates a byte space for each empty object to distinguish the memory occupied by the empty object
26 // each empty object should also have a unique memory address
27     cout << "size of p = " << sizeof(p) << endl;
28 }
29 
30 void test02() {
31     Person p;
32     cout << "size of p = " << sizeof(p) << endl;
33 }
34 
35 int main() {
36 
37     //test01();
38 
39     test02();
40 
41     system("pause");
42 
43     return 0;
44 }
45 
46 
47 // summary
48 // in C + +, member variables and member functions in a class are stored separately
49 // only non static member variables belong to class objects
50 //

 

4.3.2 this pointer

1 #include
 2 using namespace std;
 3 
 4 
 5 class Person {
 6 public:
 7     Person(int age) {
 8 
 9         //age = age; // Name conflict
The pointer to the object to which the function 10 // this belongs
11         this->age = age;  // Solve through this
12         
13     }
14 
15 person & personaddage (person & P) {// returns the P2 ontology, which needs to be returned by reference
16         this->age += p.age;
17 
18 // this refers to the pointer of P2, and * this refers to the ontology of P2;
19         return *this;
20     }
21 
22     int age;
23 
24 };
25 
26 void test01() {
27     Person p1(10);
28 cout < < P1's age is: < < P1 age << endl;
29 
30 // chain programming idea
31     Person p2(20);
32     p2.PersonAddAge(p1).PersonAddAge(p1).PersonAddAge(p1);
33 cout < < the age of P2 is: < < P2 age << endl;
34 
35 }
36 
37 int main() {
38 
39     test01();
40 
41     system("pause");
42 
43     return 0;
44 }
45 
46 // summary
47 // known:
48 // member functions and member variables are stored separately
49 // each non static member function will only produce a function instance, that is, multiple objects of the same type will share a piece of code
50 // then the question is: how does this piece of code distinguish which object is calling itself?
51 // 
52 // C + + solves the above problems through a special pointer object, this pointer
53 // this pointer points to the object to which the called member function belongs
54 // 
55 // this pointer is a pointer that implies every non static member function
56 // this pointer does not need to be defined. You can use it directly
57 // 
58 // purpose of this pointer:
59 // when a formal parameter has the same name as a member variable, it can be distinguished by the this pointer
60 // return the object itself in the non static member function of the class. You can use return * this
61 // 
62 // 
63 // other conclusions
64 // C + + hollow pointer can also call member functions, but please note whether this pointer is used
65 // if this pointer is used, it needs to be judged to ensure the robustness of the code
66 // if(this == NULL){
67 //     return;
68 // }
69 //

 

4.3.3 const modifier member function

1 #include
 2 using namespace std;
 3 
 4 
 5 class Person {
 6 public:
 7     Person() {
 8 cout < < "person's parameterless constructor!"<< endl;
 9     }
10 
11     Person(int a) {
12 cout < < "person's parameterized constructor!"<< endl;
13     }
14 
15     void showPerson() const
16     {
17 // the essence of this pointer is a pointer constant. The pointer cannot be modified
18 // add const after the member function to modify the point of this. The value pointed by the pointer cannot be modified
19         //m_ A = 100;  // After const is added, it becomes a constant function, which cannot modify member properties
20         //this->m_ A = 100;  // essence
21         this->m_ B = 100;  // Mutable can be modified after being added
22 
23     }
24 
25     void func() {
26 
27     }
28 
29     int m_A;
30     mutable int m_B;
31 
32 };
33 
34 void test01() {
35     Person p1;
36     p1.showPerson();
37 
38     const Person p2;  // Add const before the object to become a constant object
39     //p2. m_ A = 100; // An error is reported. The property of the pointer cannot be modified
40     p2.m_B = 100;
41 
42 // a constant object can only call a constant function
43 
44     p2. showPerson(); // Constant functions can be called
45     //p2. func(); // Regular objects cannot call ordinary member functions because ordinary member functions can modify properties
46 
47 }
48 
49 int main() {
50 
51     test01();
52 
53     system("pause");
54 
55     return 0;
56 }
57 
58 // summary
59 // const modifier member function
60 // constant function:
61 // add const after the member function to become a constant function
62 // member properties cannot be modified in constant functions;
63 // after adding the keyword mutable when declaring the member attribute, it can be modified in the constant function
64 // 
65 // common object:
66 // add const before declaring the object and call it a constant object
67 // constant objects can only call constant functions
68 // 
69 // 
70 //

 

4.4.1 friends

1 #include
 2 using namespace std;
 3 
 4 // buildings
 5 class Building {
 6 // goodgay global function is a good friend of building. You can access the private members of building
 7     friend void goodGay(Building* building);
 8 
 9 public:
10     Building() {
11         m_ Sittingroom = "living room";
12         m_ Bedroom = "bedroom";
13     }
14 public:
15     string m_ SittingRoom; // a living room
16 
17 private:
18     string m_ BedRoom; // bedroom
19 };
20 
21 void goodGay(Building* building) {
22 cout < < good friends global function is being accessed: "< building - > m_ SittingRoom << endl;
23 cout < < good friends global function is being accessed: "< building - > m_ BedRoom << endl;
24 }
25 
26 
27 
28 void test01() {
29     Building building;
30     goodGay(&building);
31 }
32 
33 
34 
35 int main() {
36 
37     test01();
38 
39     system("pause");
40 
41     return 0;
42 }
43 
44 
45 // summary
46 // friend, keyword friend
47 // global function as friend
48 // class as friend
49 // member function as friend
50 // 
51 //

 

Refer to the C + + tutorial of dark horse programmer