当前位置:网站首页>[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
边栏推荐
- YOLOV3学习笔记
- Une exploration intéressante de l'interaction souris - pointeur
- Opencv mouse and keyboard events
- The list of "I'm crazy about open source" was released in the first week, with 160 developers on the list
- Ruoyi interface permission verification
- Yolov1 learning notes
- Cesium Click to obtain the longitude and latitude elevation coordinates (3D coordinates) of the model surface
- 【无标题】8 简易版通讯录
- Read blog type data from mysql, Chinese garbled code - solved
- Push box games C #
猜你喜欢

Journal quotidien des questions (11)

100000 bonus is divided up. Come and meet the "sister who braves the wind and waves" among the winners

Cesium Click to obtain the longitude and latitude elevation coordinates (3D coordinates) of the model surface

数值法求解最优控制问题(一)——梯度法

Selenium - by changing the window size, the width, height and length of different models will be different

2022 CISP-PTE(三)命令执行

Mysql

vmware虚拟机C盘扩容

23 design models

【开源项目推荐-ColugoMum】这群本科生基于国产深度学习框架PaddlePadddle开源了零售行业解决方案
随机推荐
Oracle database synonym creation
DNS forward query:
SQL implementation merges multiple rows of records into one row
error C2017: 非法的转义序列
Oracle Database Introduction
Paper notes vsalm literature review "a comprehensive survey of visual slam algorithms"
Daily question brushing record (11)
Numerical method for solving optimal control problem (I) -- gradient method
Shell conditional statement
The list of "I'm crazy about open source" was released in the first week, with 160 developers on the list
HMS core helps baby bus show high-quality children's digital content to global developers
Cesium entity (entities) entity deletion method
YOLOV2学习与总结
Know flex box
Page text acquisition
简易密码锁
Fluentd facile à utiliser avec le marché des plug - ins rainbond pour une collecte de journaux plus rapide
Interesting research on mouse pointer interaction
Mysql
Use abp Zero builds a third-party login module (I): Principles






