I am learning about references in C++. So i am trying out different examples to better understand the concept. One example that i could not understand is given below:
double val = 4.55;
const int &ref = val;
std::cout << ref <<std::endl; //prints 4 instead of 4.55
I want to know what is the problem and how can i solve it?
The problem is that the reference ref
is bound to a temporary object of type int
that has the value 4
. This is explained in more detail below.
When you wrote:
const int &ref = val;
a temporary of type int
with value 4
is created and then the reference ref
is bound to this temporary int
object instead of binding to the variable val
directly. This happens because the type of the variable val
on the right hand side is double
while on the left hand side you have a reference to int
. But for binding a reference to a variable the types should match .
For solving the problem you should write:
const double &ref = val; //note int changed to double on the left hand side
The above statement means ref
is a reference to const double
. This means we cannot change the variable val
using ref
.
If you want to be able to change val
using ref
then you could simply write:
double &ref = val;
const int &ref = val;
Here you initialize ref as int type so it holds value of int type so,Implicit Type Conversion takes place.Read more about type conversion here
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.