1 concept and relationship of class and object
Class is an abstraction of a class of things with common attributes and behaviors in real life
Characteristics of class: 1. Class is the data type of object. 2. Class is a collection of objects with the same attributes and behaviors
What are the properties of an object? Attributes: various characteristics of objects. Each attribute of each object has a specific value
What is the behavior of objects? Behavior: what an object can do
Relationship between class and object:
Class: class is an abstract object of a class of things with common attributes and behaviors in real life: it is a real reality that can be seen and touched
1.1 access rights
During class design, attributes and behaviors can be controlled under different permissions. There are three kinds of access permissions:
1.public permission 2. protected permission 3. private permission
#include<iostream> using namespace std; class Person { public: string m_name; protected: string m_car; private: int m_password; public: void func() { m_name = "sss"; m_car = "aaaaaaaaaaaaaa"; m_password = 1111111111111; } }; int main() { Person p1; p1.m_name = "aaaaaaaasssssssss"; //p1.m_car = "sadsfsfsafa"; void func(); cout<<p1.m_name<<endl; //Public permission, so it can be changed system("pause"); return 0; }
1.2 difference between struct and class
In C + +, the only difference between struct and class lies in the default access permissions:
The default permissions of struct are public and class are private
#include<iostream> using namespace std; class C1 { int m_a; //private }; struct C2 { int m_a; //public }; int main() { C1 c1; //Instantiate object c1.m_a = 100; //Not accessible C2 c2; c2.m_a = 100; //Can access system("pause"); return 0; }
1.3 privatization of member attributes
Advantage 1: set all member properties to private, and you can control the read and write permissions yourself
Advantage 2: for write permission, we can detect the validity of data
#include<iostream> using namespace std; class Person { public: //Provide a public interface for you to operate //It can be read and written in the form of function //Set name public: void setname(string name) { m_name = name; } //Get name string getname() { return m_name; } //Age is read-only int getage() { int m_age = 999; return m_age; } //Write only permission / / this function interface does not have read statements void setlover(string lover) { m_lover = lover; } private: //name is readable and writable string m_name; //age read only string m_age; //Lovers only write string m_lover; }; int main() { Person p1; p1.setname("Zhang San"); cout << "Name is" << p1.getname() << endl; cout << "Age is" << p1.getage() << endl; //Set lover p1.setlover("Cangjing"); //Cout < < lover is "< < P1. M_ lover<<endl; // Not accessible!!! system("pause"); return 0; }
1.4 case - Design cube class
#include<iostream> using namespace std; //1 create cube class //2 design attributes //3 design behavior, obtain area, volume //4 judge whether the cubes are equal by using global function and member function respectively class Cube { public: //Set length void setl(int l ) { m_l = l; } //Get long int getl() { return m_l; } //Set width void setw(int w) { m_w = w; } //Get width int getw() { return m_w; } //Set high void seth(int h) { m_h = h; } //Get high int geth() { return m_h; } //Get cube area int calculaetS() { return 2 * m_l * m_w + 2 * m_w * m_h + 2 * m_l * m_h; } //Get cube volume int calculateV() { return m_l * m_w * m_h; } //The member function determines whether two cubes are equal bool issamebyclass(Cube &c2) { if (m_l == c2.getl() && m_w == c2.getw() && m_h == c2.geth())//Compare the length, width and height of itself with the length, width and height transmitted in { return true; } return false; } private: int m_l; int m_w; int m_h; }; //Use the global function to judge whether the two cubes are the same bool issame(Cube c1, Cube c2) { if (c1.getl() == c2.getl() && c1.getw() == c2.getw() && c1.geth() == c2.geth()) { return true; } return false; } int main() { //Instantiate object Cube c1; c1.seth(10); c1.setl(10); c1.setw(10); cout << "Volume is" << c1.calculaetS() << endl; cout << "Area" << c1.calculateV() << endl; //Create a second cube Cube c2; c2.seth(10); c2.setl(10); c2.setw(10); //Global function, start judgment bool ret = issame(c1, c2); if (ret) { cout<<"Global function, start judgment,The volume is equal" << endl; } else { cout << "The volume is not equal" << endl; } //Member function start judgment ret = c1.issamebyclass(c2); if (ret) { cout << "Member function start judgment,The volume is equal" << endl; } else { cout << "The volume is not equal" << endl; } system("pause"); return 0; }
1.5 case - relationship between point and circle
#include<iostream> using namespace std; //Point class class point { public: //Set x void setx(int x) { m_x = x; } //Get x int getx() { return m_x; } //Set y void sety(int y) { m_y = y; } //Get y int gety() { return m_y; } private: int m_x; int m_y; }; //Circular class class circle { public: //Set radius void setr(int r) { m_r = r; } //Get radius int getr() { return m_r; } //Set center point void setcenter(point center) { m_center = center; } //Get center point point getcenter() { return m_center; } private: int m_r; point m_center; }; //Judge the relationship between point and circle void isincircle(circle& c, point& p) { //Calculate the square of the distance between two points int distance = (c.getcenter().getx() - p.getx()) * (c.getcenter().getx() - p.getx()) + (c.getcenter().gety() - p.gety()) * (c.getcenter().gety() - p.gety()); //Calculate the square of the radius int rdistance = c.getr() * c.getr(); //Judgment relationship if (distance = rdistance) { cout<<"Point on circle" << endl; } else if (distance > rdistance) { cout << "The point is outside the circle" << endl; } else { cout << "Point in circle" << endl; } } int main2() { //Create circle circle c; c.setr(10); point center; center.setx(10); center.sety(0); c.setcenter(center); //Create point point p; p.setx(10); p.sety(10); //Judgment relationship isincircle(c, p); system("pause"); return 0; }
2 initialization and cleaning of objects
In life, the electronic products we buy will basically have factory settings. One day, we will delete some of our own information data when we are not in use to ensure security.
The object-oriented in C + + comes from life. Each object will also have initial settings and settings for cleaning data before object destruction.
2.1 constructors and destructors
Object initialization and cleaning up are also two very important security problems. An object or variable has no initial state, and the consequences of its use are unknown. Similarly, if an object or variable is used up and not cleaned up in time, it will also cause a certain security problem.
C + + uses constructors and destructors to solve the above problems. These two functions will be automatically called by the compiler to complete object initialization and cleaning. Object initialization and cleanup are things that the compiler forces us to do. Therefore, if we do not provide construction and destructor, the compiler will provide that the constructor and destructor provided by the compiler are empty implementations.
Constructor: it is mainly used to assign values to the member attributes of the object when creating the object. The constructor is automatically called by the compiler without manual call·
Destructor: it is mainly used to automatically call and perform some cleaning before the object is destroyed.
Constructor syntax: | Destructor syntax: |
---|---|
1. Constructor, no return value, no void | 1. The destructor has no return value and does not write void |
2. The function name is the same as the class name | 2. The function name is the same as the class name, and a symbol is added before the name~ |
3. The constructor can have parameters, so overloading can occur | 3. The destructor cannot have parameters, so it cannot be overloaded |
4. When the program calls the object, it will automatically call the structure without manual call, and it will only be called once | 4. The program will automatically call the destructor before the object is destroyed without manual call, and it will only be called once |
#include<iostream> using namespace std; //Constructor initialization //Destructor cleanup class person { public: //Constructor person() { cout << "Constructor" << endl; } //Destructor ~person() { cout<<"Destructor" << endl; } }; void test01() { cout <<"aaaa" << endl; person p; //After the data on the station is executed, this object will be released } int main4() { test01(); system("pause"); return 0; }
2.2 classification and calling of constructors
Two classification methods:
According to parameters, it can be divided into parametric structure and nonparametric structure
By type, it can be divided into ordinary structure and copy structure
Three call methods: bracket method, display method, implicit conversion method
#include<iostream> using namespace std; //classification class person { public: //Ordinary function //Constructor person() { cout << "Constructor" << endl; } //Parameterized constructor person(int a ) { age = a; cout << "youcan Constructor" << endl; } //copy constructor person(const person &p) { age = p.age; cout << "copy constructor " << endl; //Copy all the attributes of the incoming person to him } //Destructor ~person() { cout << "Destructor" << endl; } int age; }; //call void test01() { //1 bracket method //person p1;// Default construction //person p2(10);// Parametric structure //person p3(p2);// copy construction //Cout < < P2 age < < p2.age < < endl; //Cout < < P3 age < < p3.age < < endl; //Note 1: //Call the default constructor without adding (), because the compiler will think this is a function declaration //person p1(); //2 display method person p1;//Default construction person p2 = person(10);//Parametric structure person p3 = person(p2);//copy construction //person(10) anonymous object. Features: after the execution of the current line, the system will recycle it; //Note 2: //Do not use copy construction to initialize anonymous objects. The compiler will think that person(p3) == person p3; Object declaration //person (p3); //3 implicit transformation method person p4 = 10; //Parametric structure person p5 = p4;//copy construction } int main() { test01(); system("pause"); return 0; }
2.3 call timing of copy constructor
There are three situations in C + + when copying constructor calls
1. Initialize a new object with an already created object·
2. The method of value transfer is to transfer values to function parameters
3. Return local objects as values
#include<iostream> using namespace std; //Copy constructor call timing //1 initialize a new object with an already created object //2. Pass values to function parameters in the way of value transfer //Return local object in 3-value mode class person { public: //Constructor person() { cout << "Default constructor " << endl; } person(int age) { m_age = age; cout << "Parameterized constructor" << endl; } //copy constructor person(const person& p) { m_age = p.m_age; cout << "copy constructor " << endl; //Copy all the attributes of the incoming person to him } //Destructor ~person() { cout << "Destructor" << endl; } int m_age; }; //1 initialize a new object with an already created object void test01() { person p1(20); person p2(p1); cout << "p2 Age of" << p2.m_age<<endl; } //2. Pass values to function parameters in the way of value transfer void dowork(person p) { } void test02() { person p; dowork(p); } //3. Return a local object in the value mode. / / only the value is passed in the copy, but not the address. Therefore, the values are the same, but the addresses are different person dowork2( ) { person p1; cout<<(int*)&p1<<endl; return p1; } void test03() { person p = dowork2(); cout << (int*)&p << endl; } int main() { //test01(); test03(); system("pause"); return 0; }
2.4 constructor calling rules
By default, the C + + compiler adds at least three functions to a class
1. Default constructor (no parameters, empty function body)
2. Default destructor (no parameters, empty function body)
3. The default copy constructor copies the value of the attribute
Constructor calling rules are as follows:
If the user defines a parameter constructor, c + + no longer provides a default no parameter construct, but will provide a default copy construct,
If you define a copy constructor, C + + will not provide another constructor
#include<iostream> using namespace std; //1 create a class, and c + + will add at least three functions to each class class person { public: //person() //{ // Cout < < constructor < < endl; //} //Parameterized constructor person(int a) { age = a; cout << "Parameterized constructor" << endl; } //copy constructor //person(const person& p) //{ //age = p.age; //Cout < < copy constructor < < endl; //Copy all the attributes of the incoming person to him //} //Destructor ~person() { cout << "Destructor" << endl; } int age; }; //1 create a class, and c + + will add at least three functions to each class //void test01() //{ // person p; // p.age = 18; // person p2(p); // Cout < < P2 age is < < p2.age < < endl; //} //2 if the constructor with parameters is written, the compiler will no longer provide the default structure, but still provide the copy structure ★★★★★★★★★★★★★★★★★★★★★ // If you write a copy constructor, the compiler does not provide anything else. ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ void test02() { person p(129); person p2(p); cout << "p2 Age is" << p2.age << endl; } int main() { //test01(); test02(); system("pause"); return 0; }
2.5 light copy and deep copy
Shallow copy: a simple assignment copy operation
Deep copy: re apply for space in the heap area for copy operation
#include<iostream> using namespace std; class person { public: //Constructor person() { cout << "Constructor" << endl; } //Parameterized constructor person(int a, int height) { m_age = a; m_height = new int(height); cout << "youcan Constructor" << endl; } //There was no write copy constructor before, which is the system's default garbage copy constructor. //Implement the copy constructor to solve the problems caused by shallow copy person(const person& p) { cout<<"Copy constructor call, myself" << endl; m_age = p.m_age; //m_height = p.m_height; The compiler implements this line of code by default //Deep copy operation m_height = new int(*p.m_height); //Apply for a new piece of memory shenkaobei } //Destructor ~person() { //Destruct the code to release the data opened up in the heap area if (m_height != NULL) { delete m_height; m_height = NULL; } cout << "Destructor" << endl; } int m_age; int* m_height; }; void test01() { person p1(18, 160); cout << "p1 Your age is" <<p1.m_age<< "Height" <<*p1.m_height<< endl; person p2(p1); //Shallow copy?? cout << "p2 Your age is" << p2.m_age <<"Height" << *p2.m_height<< endl; } int main() { test01(); system("pause"); return 0; }
2.6 initialization list
Function: C + + provides initialization list syntax to initialize attributes
Syntax: constructor (): Property 1 (value 1), property 2 (value 2)
#include<iostream> using namespace std; class person { public: //Traditional initialization operation //person(int a, int b, int c) //{ // m_a = a; // m_b = b; // m_c = c; //} //Initialization list initialization properties person() : m_aa(10), m_bb(20), m_cc(30) { } //Initialization list, initialization properties, sublimation person(int aa, int bb, int cc) : m_aaa(aa), m_bbb(bb), m_ccc(cc) { } int m_a; int m_b; int m_c; int m_aa; int m_bb; int m_cc; int m_aaa; int m_bbb; int m_ccc; }; void test01() { person p(10, 20, 30); cout << "m_a" << p.m_a << endl; cout << "m_b" << p.m_b << endl; cout << "m_c" << p.m_c << endl; } void test02() { person p; cout << "m_aa" << p.m_aa << endl; cout << "m_bb" << p.m_bb << endl; cout << "m_cc" << p.m_cc << endl; } void test03() { person p(99,88,55); cout << "m_aa" << p.m_aaa << endl; cout << "m_bb" << p.m_bbb << endl; cout << "m_cc" << p.m_ccc << endl; } int main() { test03(); system("pause"); return 0; }
2.7 class objects as class members
A member in a C + + class can be an object of another class, which we call an object member.
Class B has object A as A member and A as an object member.
Then, when creating A B object, which is the order of construction and Deconstruction of A and B?
#include<iostream> using namespace std; //Mobile phone class class phone { public: phone(string pname) { cout << "phone Call of constructor for" << endl; m_pname = pname; } //Destructor ~phone() { cout << "phone Destructor" << endl; } //Mobile phone brand name string m_pname; }; //human beings class person { public: // phone m_phone = pname implicit conversion person(string name, string pname) :m_name(name), m_phone(pname) { cout <<"person Call of constructor for" << endl; } //Destructor ~person() { cout << "person Destructor" << endl; } //xingming string m_name; //phone phone m_phone; }; // When other class objects are members of this class, the class object is constructed first, and then the class object itself is constructed, and the destructor??????? void test01() { person p("Zhang San", "Apple max"); cout << p.m_name << "Take it" << p.m_phone.m_pname << endl; } int main() { test01(); system("pause"); return 0; }
2.8 static members
Static members are called static members by adding the keyword static before member variables and member functions
Static members are divided into:
Static member variable | Static member function |
---|---|
All objects share the same data. Allocate memory at compile time | All objects share the same function |
Inner class declaration, outer class initialization· | Static member functions can only access static member variables |
2.8.1 static member variables (1)
#include<iostream> using namespace std; //Static member variable class person { public: //1 all objects share the same data static int m_a; private: static int m_b; }; int person::m_a = 100; int person::m_b = 200; void test01() { person p; cout<<p.m_a<<endl; person p2; p2.m_a = 200; cout << p2.m_a << endl; cout << p.m_a << endl; } void test02() { //Static member variables do not belong to an object, and all objects share the same data //1. Access by object person p; cout <<p.m_a<<endl; //2. Access by class name cout << person::m_a << endl; cout << person::m_a << endl; } int main() { test01(); system("pause"); return 0; }
2.8.2 static member variables (2)
#include<iostream> using namespace std; //Static member function class person { public: //1 all objects share the same data static void func() { m_a = 100; //Static members can access static member variables //m_b = 200; // Static member functions cannot access non static member variables, and it is impossible to distinguish which object is m_b cout << "static Call of" << endl; } static int m_a; int m_b ; private: static void func2() { cout << "Private static Call of" << endl; } }; int person::m_a = 100; void test01() { //1. Access by object person p; p.func(); //2. Access by class name person::func(); //person::func2(); // Private cannot be accessed!!!!!!!! } int main() { test01(); system("pause"); return 0; }