当前位置:网站首页>[classes and objects] explain classes and objects in simple terms
[classes and objects] explain classes and objects in simple terms
2022-07-03 06:39:00 【Crevice`】
Learn navigation
1. What is an object ?
Object is an abstract concept , It means anything that exists . Everything in the world can be an object , In the real world , A thing that can be seen everywhere is an object , Object is the existence of things Entity , A specific person is an object , A specific book can also be an object ……
2. What is a class? ?
Classes are encapsulating objects “ attribute ” and “ Behavior ” The carrier of . On the other hand , Having the same properties and behavior A class Entities are called classes . for instance :
( Picture from the Internet )
The range of classes can be large or small , As long as they have the same attributes and behaviors, they can be classified into one class . If we will Instantiation , You can get a specific object .
3. How to define a class ?
Classes are defined in two ways , Early use struct To define a class , Later introduced keywords class To define a class , Now we are still used to using class To define a class .
① use class Defining classes
class className { // The class body : It consists of member functions and member variables }; // Be sure to pay attention to the semicolon behind② use struct Defining classes :
struct dog { // action void eat() { cout << "The dog is eating!" << endl; } // attribute int _age; char _name[10]; };C++ The structure in is upgraded to class :
The structure name can be directly used as the type
struct ListNode { int val; ListNode* next; // C++ There is no need to add struct };“ Structure ” Function can be defined in
Of course, for compatibility C Language ,C The operation of structure in language is the same
4. encapsulation
stay C In language , Data and methods are separated . When data and method are separated , Although users have higher degrees of freedom , But the Literacy Requirements for users are also higher . An example of image : If there is no fence in the scenic spot , There is no fixed access , Then people can go in and out at will , Vandalism of scenic spots ; Corresponding to our program , There is a risk of data being tampered .
We can see ,C++ Classes in put data and methods together , adopt Access qualifier To protect some member variables and member functions , Thus ensuring the integrity of the internal data structure of the class , Prevent external operations from interfering with internal data .
5. Access qualifier
There are three types of access qualifiers , There are several points to pay attention to :
- public Decorated members can be accessed directly outside the class
- protected and private Decorated members cannot be directly accessed outside the class ( In package protected and private The function of is similar )
- There can be multiple access qualifiers in a class , The access scope starts from where the access qualifier appears until the next access qualifier appears
- class The default access rights of are private,struct by public( because struct To be compatible with C)
class classname { public: // …… The access rights of member functions are usually public private: // …… The access rights of member variables are usually private };6. Definition domain of class
Because the class is a whole , When finding variables, you will find them in the whole class , So member functions can be defined anywhere .
7. Definition of member function
There are also two ways to define member functions :
① Defined in class
class student { public: void init(int age, int score) { _age = age; _score = score; } private: int _age; int _score; };
- The functions defined in the class are all inline functions by default . This also points the way for us to write code , The functions defined in the class are suitable for short functions
- Member variables are customarily preceded by “_”, otherwise init The parameter names of functions are awkward
② Define... Outside the class
class student { public: void init(int age, int score); private: int _age; int _score; }; void student::init(int age, int score) { _age = age; _score = score; }
Put declaration in class , The definition is placed outside the class
To illustrate that this function is a member function of a class , You need to add the class name and scope decomposition operator before the function name
8. Instantiation
// For example, use the above ListNode Class to create objects ; int main() { ListNode node; }reflection : Whether member variables in a class are defined or declared ?
【 answer 】 Whether to define or declare depends on whether to open up space . When creating classes and opening up space for member variables , So it's just a statement , It is only defined when instantiating
9. How to calculate the size of an object ?
There are both member variables and member functions in the object . For member variables , Each object must be independent and different from each other , However, member functions only need to store a copy in a fixed place . The specific storage mode is shown in the figure below . When calculating the size of member variables, you still need to follow the rules of memory alignment .
Under disassembly, we can observe , When calling member functions for multiple objects created by the same class ,call The function addresses corresponding to the instructions are the same .
10. this Introduction of pointer
【 problem 】 Member functions are stored in the common code area , So there is no distinction between different objects in the function body , So how does a function know which object it operates on ?
【 resolvent 】C++ Introduce keywords this The pointer . Every The static Member functions have a hidden parameter this The pointer , Calling The static A pointer parameter will also be passed in by default when the member function , The function of this pointer is to point to the current object .
Let's illustrate with the following example :class Date { public : void Display () { cout <<_year<< "-" <<_month << "-"<< _day <<endl; } void SetDate(int year , int month , int day) { _year = year; _month = month; _day = day; } private : int _year ; // year int _month ; // month int _day ; // Japan };
Feature summary :
① this The function of pointers is to ensure that each object has its own data members , But share the code that processes this data
② Static member functions ( The function name is prefixed with static) Shared by all objects , So there was no this The pointer
③ this Pointers are automatically passed by the compiler , Cannot be written in formal parameters , You can't pass parameters manually . but this Pointers can be used
It can also prove that this The pointer Point to current object
边栏推荐
- Mysql database binlog log enable record
- Characteristics and isolation level of database
- HMS core helps baby bus show high-quality children's digital content to global developers
- 每日刷题记录 (十一)
- Cesium entity (entities) entity deletion method
- 【code】if (list != null && list.size() > 0)优化,集合判空实现方式
- 致即将毕业大学生的一封信
- 【无标题】5 自用历程
- Scripy learning
- Local rviz call and display of remote rostopic
猜你喜欢

Operation principle of lua on C: Foundation

After the Chrome browser is updated, lodop printing cannot be called

Yolov1 learning notes

使用conda创建自己的深度学习环境

HMS core helps baby bus show high-quality children's digital content to global developers

Summary of remote connection of MySQL

Click cesium to obtain three-dimensional coordinates (longitude, latitude and elevation)

Personally design a highly concurrent seckill system

golang操作redis:写入、读取kv数据

Reinstalling the system displays "setup is applying system settings" stationary
随机推荐
【无标题】5 自用历程
MATLAB如何修改默认设置
Summary of UI module design and practical application of agent mode
Various usages of MySQL backup database to create table select and how many days are left
有意思的鼠標指針交互探究
第8章、MapReduce 生产经验
Scripy learning
DBNet:具有可微分二值化的实时场景文本检测
Redis cluster creation, capacity expansion and capacity reduction
Luogu problem list: [mathematics 1] basic mathematics problems
Reinstalling the system displays "setup is applying system settings" stationary
Selenium ide installation recording and local project maintenance
Local rviz call and display of remote rostopic
Some thoughts on machine learning
opencv鼠标键盘事件
error C2017: 非法的转义序列
Opencv mouse and keyboard events
Create your own deep learning environment with CONDA
Example of joint use of ros+pytoch (semantic segmentation)
Understand software testing






