当前位置:网站首页>[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
边栏推荐
- After the Chrome browser is updated, lodop printing cannot be called
- Cesium Click to obtain the longitude and latitude elevation coordinates (3D coordinates) of the model surface
- Printer related problem record
- SQL实现将多行记录合并成一行
- 方差迭代公式推导
- 爬虫代码基础教学
- 冒泡排序的简单理解
- Common interview questions
- IC_EDA_ALL虚拟机(丰富版):questasim、vivado、vcs、verdi、dc、pt、spyglass、icc2、synplify、INCISIVE、IC617、MMSIM、工艺库
- Fluentd facile à utiliser avec le marché des plug - ins rainbond pour une collecte de journaux plus rapide
猜你喜欢
Chapter 8. MapReduce production experience
vmware虚拟机C盘扩容
Redis cluster creation, capacity expansion and capacity reduction
卡特兰数(Catalan)的应用场景
Operation principle of lua on C: Foundation
Personally design a highly concurrent seckill system
The dynamic analysis and calculation of expressions are really delicious for flee
Use abp Zero builds a third-party login module (I): Principles
论文笔记 VSALM 文献综述《A Comprehensive Survey of Visual SLAM Algorithms》
SQL实现将多行记录合并成一行
随机推荐
Know flex box
Code management tools
Shell conditional statement
Create your own deep learning environment with CONDA
Interesting research on mouse pointer interaction
IC_EDA_ALL虚拟机(丰富版):questasim、vivado、vcs、verdi、dc、pt、spyglass、icc2、synplify、INCISIVE、IC617、MMSIM、工艺库
Read blog type data from mysql, Chinese garbled code - solved
Decision tree of machine learning
vmware虚拟机C盘扩容
golang操作redis:写入、读取kv数据
[untitled] 5 self use history
Derivation of variance iteration formula
Unittest attempt
Summary of UI module design and practical application of agent mode
Nacos service installation
The most classic 100 sentences in the world famous works
Time format record
opencv
[5g NR] UE registration process
HMS core helps baby bus show high-quality children's digital content to global developers