简体   繁体   中英

What is the usage of references and pointers to constants?

In C++ Primer book I read about references to constants such as these:

const int ci = 1024;
const int &r1 = ci;

The same goes for pointers.

const double pi = 3.14;
const double *ptr = π

I wonder, what is the usage of these references if you can't even change the value of the constant? Why would you even want to create pointer to a constant?

I wonder, what is the usage of these references if you can't even change the value of the constant

The most common use case are functions. A function with an argument can be much more useful than a function that only uses a constant.

But passing a constant into a function call (thereby binding the argument to that constant) is also useful:

void foo(const int &r1);

// call using a constant
foo(ci);

Note that there is rarely a need to use references to integers, as usually one is only interested in the value of an integer, and don't care about the identity of the object.

The indirection that references and pointers provide makes runtime polymorphism possible. You'll learn about that when you study object oriented programming.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM