当前位置:网站首页>[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
边栏推荐
- pytorch练习小项目
- YOLOV2学习与总结
- The most classic 100 sentences in the world famous works
- 剖析虚幻渲染体系(16)- 图形驱动的秘密
- 远端rostopic的本地rviz调用及显示
- Create your own deep learning environment with CONDA
- golang操作redis:写入、读取hash类型数据
- 100000 bonus is divided up. Come and meet the "sister who braves the wind and waves" among the winners
- Advanced technology management - do you know the whole picture of growth?
- The list of "I'm crazy about open source" was released in the first week, with 160 developers on the list
猜你喜欢

远端rostopic的本地rviz调用及显示

SSH link remote server and local display of remote graphical interface

【类和对象】深入浅出类和对象

Scroll view specifies the starting position of the scrolling element

Docker advanced learning (container data volume, MySQL installation, dockerfile)

ssh链接远程服务器 及 远程图形化界面的本地显示

2022 cisp-pte (III) command execution

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

Scripy learning

YOLOV2学习与总结
随机推荐
The difference between CONDA and pip
保险公司怎么查高血压?
Numerical method for solving optimal control problem (I) -- gradient method
堆排序和优先队列
Docker advanced learning (container data volume, MySQL installation, dockerfile)
vmware虚拟机C盘扩容
Pytest attempts to execute the test case without skipping, but the case shows that it is all skipped
Use selenium to climb the annual box office of Yien
Know flex box
【无标题】5 自用历程
JMeter linked database
Introduction to software engineering
Scroll view specifies the starting position of the scrolling element
Shell conditional statement
Mysql
UNI-APP中条件注释 实现跨段兼容、导航跳转 和 传参、组件创建使用和生命周期函数
【LeetCode】Day93-两个数组的交集 II
Unit test framework + Test Suite
SQL实现将多行记录合并成一行
方差迭代公式推导





