当前位置:网站首页>Just remember Balabala
Just remember Balabala
2022-07-06 10:30:00 【Don't understand anything】
const References to
Usually : The type of reference must strictly match the object type it is bound to
int a = 100;
int &val = a;
But constant references don't need .
double i = 14.42;
const int& i0 = i;
cout << i0;The final output is 14;
in other words , The constant reference will carry out type conversion on the referenced object whose type does not match .
Here i0 Quoted a int Object of type , however i It's a double floating point number . So to ensure that i0 Bound to an integer , The compiler changes the above code into the following form :
const int temp = i; // Use variables to realize type conversion
const int &i0 = temp; // Reuse i0 For temporary quantity ( At this time, the type is matched ) Binding It's nice .
in addition , At this time, constant references , In fact, it seems not to be a constant in the strict sense , Although but , We still can't directly deal with const References to objects , Assign a value , Or other operations that try to change constants . however , You can change the value of constants in other ways
#include<iostream>
using namespace std;
int main() {
int val = 100;
const int &cval = val;
cout << cval << endl;
int& ival = val;
++ival;
cout << cval;
}
The output is
100
101Or directly to the original object val Assign a value , It will change too. const The value of the reference of the object .
Add : Usually , References cannot be assigned with literal values , But constant references are ok
const int &val = 42;
cout << val;The result is 42
in other words , Objects cannot be changed by constant references , It doesn't matter whether it's bound to a literal or an object , Anyway, we can't make changes, so there is no meaningless change .
Pointers and const
const double pi = 3.14;// Initialize double constant pi
const double* cptr = π// You can only use a pointer to a constant to store the address of a constant object
double a = 100;
cptr = &a;
cout << *cptr; // Output 100;
++ *cptr;// Constant cannot be assigned
The type of the pointer must be consistent with the type of the object it refers to . But there are two exceptions , The first exception is Allow a pointer to a constant to point to a non constant object .
Look at the code above , We found that , pointer to const , It only requires that the value of the object cannot be changed through this pointer , We can even change the pointer directly , Point to a very large number of objects , There is no binding relationship between the two .

This is the picture I drew myself , My own understanding , I don't know if there are any mistakes ,const The address of the constant must be stored in const * Type in the , however const * You can also store a very large number of addresses . But no matter whose address it is stored , Can't pass the dereference character “*”, Yes Object . and const Same reference , Although it can't be directly through the pointer pair Object , But there are other ways to change the object , It doesn't matter .
there const Just saying : This pointer points to a constant , This constant cannot be arbitrarily changed through this pointer . And what to say next const Pointers are very different .
In the book : A pointer or reference to a constant , Just pointers or references “ Be opinionated ” only , They feel that they point to constants , So consciously do not change the value of the object .
const The pointer
Actually, the above , Our focus is on the type . So we can change the direction of the pointer . What to say next const The pointer , Is to set the pointer itself as a constant . Constant pointers are the same as constants , Must be initialized , And after initialization , The address stored in the pointer can no longer be changed .
#include<iostream>
using namespace std;
int main() {
int val = 100;
int* const cptr = &val; // hold * Put it before the keyword to indicate that the pointer is a constant
// This writing form implies a layer of meaning
// That is, the constant is the value of the pointer itself ( The address of the object pointed to )
// Instead of pointing to the object
// The object pointed to can be modified by the dereference character .
const double pi = 3.14;
// The first one here const This ensures that this constant cannot be modified by a pointer
// the second const To ensure the , The address of this pointer , Already bound to this pointer , Can't change .
const double* const pip = π
//pip = &val; illegal , because pip Is a constant pointer , After being initialized , You cannot change the value
//*pip = 1111; illegal , It points to a double constant , Cannot be modified by this pointer , The value of the object he points to .
int* const cptr1 = &val;
*cptr1 = 100;
cout << *cptr1;// Output 100, The type here int
// Means that after dereferencing, you get a int Variable of type , You can change the value
// If it is const int , Then the value cannot be modified
}
I feel this kind of definition statement , Look from right to left , It's a good choice .
top floor const
As mentioned earlier , The pointer itself is an object , It can point to another object . So the pointer itself is a constant , And whether the pointer refers to a constant is two independent problems .
Bottom const: Indicates that the object pointed to is a constant , Related to composite types such as pointers and references .
top floor const: Indicates that the pointer itself is a constant , top floor const Any object can be represented as a constant , For any data type .
What's more special is : The pointer can be either the bottom layer const, It can also be the top floor const
int const a = 100;
cout << a;
// I found that more than pointers can be used after types const, Other data types can also .Used to declare references to const It's all at the bottom const, Taking the address of constant object is also const
const int ci =100;
&ci: Bottom const
int const a = 100; int b = a; const int* c = &a;// top floor const You can give it to the bottom const initialization . //int* const d = c;// Bottom const Not to the top const initialization ( Copy ), Because because c Itself is the bottom layer const, It is itself a variable // however d It's the top floor const, A constant . So variables cannot be copied to a constant . // Let's do another example , Examples cited const int& bval = b;// References are all at the bottom const const int* const p = &bval; //int* const p2 = &bval; p2 It's a top floor const, however bval It's a ground floor const, Cannot perform
边栏推荐
- Sed text processing
- [C language] deeply analyze the underlying principle of data storage
- If someone asks you about the consistency of database cache, send this article directly to him
- Texttext data enhancement method data argument
- MySQL real battle optimization expert 08 production experience: how to observe the machine performance 360 degrees without dead angle in the process of database pressure test?
- MySQL Real Time Optimization Master 04 discute de ce qu'est binlog en mettant à jour le processus d'exécution des déclarations dans le moteur de stockage InnoDB.
- MNIST implementation using pytoch in jupyter notebook
- Super detailed steps to implement Wechat public number H5 Message push
- Several errors encountered when installing opencv
- Nanny hand-in-hand teaches you to write Gobang in C language
猜你喜欢

How to make shell script executable

MySQL31-MySQL事务日志

Use JUnit unit test & transaction usage

MySQL底层的逻辑架构

MySQL实战优化高手12 Buffer Pool这个内存数据结构到底长个什么样子?

Notes of Dr. Carolyn ROS é's social networking speech

MySQL combat optimization expert 02 in order to execute SQL statements, do you know what kind of architectural design MySQL uses?

UnicodeDecodeError: ‘utf-8‘ codec can‘t decode byte 0xd0 in position 0成功解决
![16 medical registration system_ [order by appointment]](/img/7f/d94ac2b3398bf123bc97d44499bb42.png)
16 medical registration system_ [order by appointment]
![[Julia] exit notes - Serial](/img/d0/87f0d57ff910a666fbb67c0ae8a838.jpg)
[Julia] exit notes - Serial
随机推荐
Chrome浏览器端跨域不能访问问题处理办法
CDC: the outbreak of Listeria monocytogenes in the United States is related to ice cream products
评估方法的优缺点
The appearance is popular. Two JSON visualization tools are recommended for use with swagger. It's really fragrant
What is the current situation of the game industry in the Internet world?
MySQL实战优化高手02 为了执行SQL语句,你知道MySQL用了什么样的架构设计吗?
ByteTrack: Multi-Object Tracking by Associating Every Detection Box 论文阅读笔记()
Introduction tutorial of typescript (dark horse programmer of station B)
Pytorch RNN actual combat case_ MNIST handwriting font recognition
17 medical registration system_ [wechat Payment]
The 32 year old programmer left and was admitted by pinduoduo and foreign enterprises. After drying out his annual salary, he sighed: it's hard to choose
MySQL Real Time Optimization Master 04 discute de ce qu'est binlog en mettant à jour le processus d'exécution des déclarations dans le moteur de stockage InnoDB.
The programming ranking list came out in February. Is the result as you expected?
软件测试工程师必备之软技能:结构化思维
13 medical registration system_ [wechat login]
MySQL combat optimization expert 06 production experience: how does the production environment database of Internet companies conduct performance testing?
MySQL real battle optimization expert 08 production experience: how to observe the machine performance 360 degrees without dead angle in the process of database pressure test?
Mexican SQL manual injection vulnerability test (mongodb database) problem solution
【C语言】深度剖析数据存储的底层原理
该不会还有人不懂用C语言写扫雷游戏吧