当前位置:网站首页>Classes and objects (I) detailed explanation of this pointer
Classes and objects (I) detailed explanation of this pointer
2022-07-06 05:41:00 【Less debug every day】
Indexes
The definition of a class
stay C In language , A structure can only define variables , But in C++ The middle structure can not only define variables , You can also define functions , At this point, we call the structure class and use the keyword class Express .
class className
{
// The class body : It consists of member functions and member variables
};
The general composition is shown above
eg
class STu
{
void Print()
{
cout << "printf" << endl;
}
int a;
int b;
int c;
};
At the same time, the class name can be directly typed STu a; STu b;
notes : If the definitions of function declarations are all in the class , Then this function will be regarded by the compiler as Inline function Handle , Therefore, it is generally recommended to separate statements and definitions .
Access qualifier
Access qualifier , seeing the name of a thing one thinks of its function , It is to limit whether the variables or functions in the class can be directly accessed outside the class , Here are three access qualifiers and their functions .
Be careful : Access qualifiers are only useful at compile time , When the data is mapped to memory , There is no difference in access qualifiers
Be careful public The default access is private ,struct The default access permission is public ( because struct To be compatible with C)
Class encapsulation
encapsulation : Organically combine data and methods of operating data , Hide object properties and implementation details , Only expose interfaces to interact with objects .
Why package ?
stay C Language time , When we simulate the implementation of stack area ,
struct Stack
{
int* a;
int top;
int capacity;
};
struct Stack q;
When we need the elements at the top of the stack , Sometimes we just write q.a[top] perhaps q.a[top-1]
, It depends on how the writer initializes top Initialize to -1 still 0, In this case, it is very inconvenient for users , And once there are more functions , Each has its own implementation and representation , therefore C Language is very free , Because its data and method are separated , It mainly depends on the quality of programmers , To avoid that ,C++ Combine data and methods directly , Public interface , The function you want users to use is set to public, Functions or variables that you don't want users to see are set to private .
eg:( Stack )
class Stack
{
public:
void Push(){
}// Insert pop-up we want users to use this function of the stack, so we set it to public , Users can access directly outside the class
void Pop(){
}
int Top(){
}
private:
void Check_capacity() {
};// Check whether it needs to be expanded. We don't want users to use , So set it as private
int* a;// If we don't want users to use member variables, we also set them to private
int _top;
int _capacity;
};
So encapsulation is essentially a kind of Management , We directly set up a public interface for users to use , Settings that you don't want users to use are private , Make the user use the unique interface .
Scope of class
Class defines a new scope , All members of a class are in the scope of the class . Define members outside the class , Need to use :: The scope resolver indicates which class domain the member belongs to
The above mentioned , Function in class , It is generally recommended to separate declarations from definitions , When defining, we need to add in front of it which class domain this function belongs to .
eg
void Stu::Print()
{
}
Class instantiation
The process of creating objects with class types , Called class instantiation
- Class is just a model thing , Defines which members of the class , Defining a class does not allocate the actual memory space to store it
- A class can instantiate multiple objects , Instantiated object Take up actual physical space , Store class member variables
understand The difference between declaration and definition opens up space .
The above mentioned opens up space for variables , What about functions ? See the following how to calculate the size of a class
Class size calculation
put questions to
Suppose the class is like this :class A3{};
At this time, the class has no member variables , At this point, the compiler will give the class a byte placeholder , Indicates that it existed .
This The pointer
1,This Introduction of pointer
First define a date class
class Date
{
public:
void Init(int year, int month, int day)
{
_year = year;
_month = month;
_day = day;
}
void Print()
{
cout << _year << "-" << _month << "-" << _day << endl;
}
private:
int _year;
int _month;
int _day;
};
int main()
{
Date A;
Date B;
A.Init(2022, 7, 5);
A.Print();
B.Init(2022, 7, 4);
B.Print();
return 0;
}
As mentioned above , The functions called by different classes of objects are the same function , But the member variables in class objects are different , How does the function know A The member variable used when calling the function is at this time A The variable of ?
C++ Introduced in This Pointers solve this problem .
namely
C++ The compiler gives each “ Non static member functions “ Added a hidden pointer parameter
Count , Let the pointer point to the current object ( The object that the function calls at run time ), Operation of all member variables in the function body , All through the
Pointer to access . But all operations are transparent to users , That is, the user does not need to deliver , Compiler autocompletes .
eg
That is, the compiler will automatically pass the address of the object itself to the function as an implicit parameter , Even if we
You didn't write This Pointer compiler also adds this Of , It is an implicit parameter of a non static member function , Visits to members were made through this Conduct .
2,This Characteristics
1.this The type of pointer : type const
namely Date*const this
namely this The pointer itself cannot be changed , But the object it points to can be changed
2, Only in “ Member functions ” Internal use of
Global function 、 Static functions cannot be used this. In fact, the first parameter of the member function in the class is (Dateconst this) We can also see from the above example
3,this Pointer is essentially a parameter of a member function , When an object calls a member function , Pass the object address as an argument to this Shape parameter . So objects don't store this The pointer is thus visible ,this Construct... Before the start of the member function , Clear after the end of the member function . however this Pointers themselves are somewhat different from static functions , Compilers usually do this Pointer to do some optimization , Generally, the compiler passes through ecx Register auto transfer , No need for users
Pass therefore ,this Pointer transfer efficiency is relatively high
Interview questions :
1,this Where the pointer is stored
The above story ,this A pointer is actually a formal parameter of a member function , that this Pointers may be stored in the stack ,
2, Some compilers use register optimization , all this Pointers may also be stored in registers
Is there any mistake in the following procedure ?
class A
{
public:
void PrintA()
{
cout << _a << endl;
}
void Show()
{
cout << "Show()" << endl;
}
private:
int _a;
};
int main()
{
A* p = nullptr;
p->PrintA();
p->Show();
}
The above program can work normally , because show Functions are placed in the public code area , Is not a variable in a class object , although p Is a null pointer , And the message is p, then Show Function this Pointer acceptance , You can still call functions , There is no dereference of null pointers , So there's no mistake , It's going to work
But if you say main If you change the content in the function, an error will be reported
It's not easy to create , I hope you can give me more support , Crab
边栏推荐
- Solution of QT TCP packet sticking
- PDK process library installation -csmc
- Questions d'examen écrit classiques du pointeur
- 27io stream, byte output stream, OutputStream writes data to file
- [Jiudu OJ 07] folding basket
- 改善Jpopup以实现动态控制disable
- B站刘二大人-Softmx分类器及MNIST实现-Lecture 9
- Jushan database appears again in the gold fair to jointly build a new era of digital economy
- Jvxetable implant j-popup with slot
- Promotion hung up! The leader said it wasn't my poor skills
猜你喜欢
B站刘二大人-线性回归 Pytorch
Summary of deep learning tuning tricks
Modbus protocol communication exception
26file filter anonymous inner class and lambda optimization
Redis消息队列
注释、接续、转义等符号
无代码六月大事件|2022无代码探索者大会即将召开;AI增强型无代码工具推出...
29io stream, byte output stream continue write line feed
B站刘二大人-Softmx分类器及MNIST实现-Lecture 9
巨杉数据库再次亮相金交会,共建数字经济新时代
随机推荐
Closure, decorator
Notes, continuation, escape and other symbols
Questions d'examen écrit classiques du pointeur
59. Spiral matrix
Game push image / table /cv/nlp, multi-threaded start
How to download GB files from Google cloud hard disk
Vulhub vulnerability recurrence 73_ Webmin
Anti shake and throttling are easy to understand
Safe mode on Windows
UCF (summer team competition II)
LeetCode_字符串反转_简单_557. 反转字符串中的单词 III
Go language -- language constants
嵌入式面试题(四、常见算法)
Codeless June event 2022 codeless Explorer conference will be held soon; AI enhanced codeless tool launched
The ECU of 21 Audi q5l 45tfsi brushes is upgraded to master special adjustment, and the horsepower is safely and stably increased to 305 horsepower
MySQL advanced learning summary 9: create index, delete index, descending index, and hide index
B站刘二大人-反向传播
What impact will frequent job hopping have on your career?
[imgui] unity MenuItem shortcut key
Jvxetable用slot植入j-popup