Msgstr "not constant lvalue type reference cannot bind" error with reference (Type &), but not pointer (Type *)

I get this error "Non-const lvalue for input" Cell "cannot bind to the temporary type" Cell * "with this code:

class RegionHolder { public: RegionHolder(Region& Region1):m_RegionCellNOO(&(Region1.m_NOO)) ~RegionHolder(); protected: Cell & m_RegionCellNOO; // difference is here }; 

but not with this:

 class RegionHolder { public: RegionHolder(Region& Region1):m_RegionCellNOO(&(Region1.m_NOO)) ~RegionHolder(); protected: Cell * m_RegionCellNOO; // difference is here }; 

I do not understand the problem and would like to use links, not pointers.

thanks

+4
source share
2 answers

You forgot to show us the definition, but supposedly Region1.m_NOO is an object of type Cell . In the first example, you take its address and try to use the resulting pointer to initialize the link. Links are not initialized with pointers, but with the object itself:

 RegionHolder(Region& Region1):m_RegionCellNOO(Region1.m_NOO) {} // ^ no & ^^ don't forget that 

There is one caveat with using references, not pointers: they cannot be assigned, and therefore your class is not. This is often not a problem; but if you need your class to assign, then you will need to use a pointer.

+5
source

The unary operator & gets a pointer to a variable. So, in C ++ (as in C) a = &b gets a pointer to b and stores this value in a , therefore, if b is of type int , a must be of type int* . Link assignment, on the other hand, is implicit, so if a is of type int& , you just need to write a=b to make a reference to b . Therefore, in your case, you need to rewrite your constructor as

 RegionHolder(Region& Region1):m_RegionCellNOO(Region1.m_NOO) {} 

However, I think you're better off using pointers than the links here, and trying to use C ++ without getting used to pointers is a very bad idea. Therefore, I suggest that you take the time to calm down with pointers instead of trying to avoid them.

+1
source

All Articles