What does the following code mean in C ++?

struct Dog{ int a; int b; }; int Dog::*location = &Dog::a Dog* obj1 = new Dog; obj1->*location = 3; 

What does &Dog::a mean?

+4
source share
3 answers

It creates a pointer to an element that looks like a pointer to a data element of a class, but the class instance is not yet defined, it's just an offset. (Note that when combined with multiple inheritance or virtual inheritance, it becomes quite complicated than a simple offset, but the compiler develops the details.)

Notice the dereference-pointer-operator operator ->* used on the last line, where the class instance is combined with the member pointer to get a specific data item for a specific instance.

+4
source

The location variable is known as the "item data pointer". This is a pointer to something inside the structure, but it does not make sense if it is not used with the actual pointer of the object. Using *location alone will not be enough information to resolve the actual address, but obj1->*location refers to the actual location.

+2
source

& means to do something.

-2
source

Source: https://habr.com/ru/post/1345649/


All Articles