当前位置:网站首页>[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
边栏推荐
- JMeter performance automation test
- Decision tree of machine learning
- Advanced technology management - do you know the whole picture of growth?
- Selenium - by changing the window size, the width, height and length of different models will be different
- New knowledge! The virtual machine network card causes your DNS resolution to slow down
- Interesting research on mouse pointer interaction
- 机器学习 | 简单但是能提升模型效果的特征标准化方法(RobustScaler、MinMaxScaler、StandardScaler 比较和解析)
- [LeetCode]404. 左叶子之和
- Summary of remote connection of MySQL
- Yolov2 learning and summary
猜你喜欢

每日刷題記錄 (十一)

IC_EDA_ALL虚拟机(丰富版):questasim、vivado、vcs、verdi、dc、pt、spyglass、icc2、synplify、INCISIVE、IC617、MMSIM、工艺库

Install VM tools

Scroll view specifies the starting position of the scrolling element

Use abp Zero builds a third-party login module (I): Principles

golang操作redis:写入、读取hash类型数据

剖析虚幻渲染体系(16)- 图形驱动的秘密

In depth analysis of kubernetes controller runtime

Chapter 8. MapReduce production experience

Docker advanced learning (container data volume, MySQL installation, dockerfile)
随机推荐
认识弹性盒子flex
2022 cisp-pte (III) command execution
【类和对象】深入浅出类和对象
Judge whether the date time exceeds 31 days
. Net program configuration file operation (INI, CFG, config)
Oracle database synonym creation
The mechanical hard disk is connected to the computer through USB and cannot be displayed
SQL实现将多行记录合并成一行
[set theory] relational closure (relational closure solution | relational graph closure | relational matrix closure | closure operation and relational properties | closure compound operation)
Pdf files can only print out the first page
error C2017: 非法的转义序列
Some thoughts on machine learning
简易密码锁
[C /vb.net] convert PDF to svg/image, svg/image to PDF
Request weather interface format, automation
[untitled] 5 self use history
爬虫代码基础教学
Daily question brushing record (11)
DNS forward query:
Printer related problem record






