C++ Pointer to member of a member?
-
25-06-2021 - |
Pregunta
Suppose I have two classes:
class A
{
int x;
int y;
};
class B
{
int z;
A ref;
};
Suppose I also have a function that accepts a pointer-to-member integer of B, like so:
void doSomethingToB(B* object, int B::* val)
{
if(val)
{
std::cout << object.*val;
}
}
Would there be a way that I could point to a member of ref
inside B?
Like, int B::* ptr = &(B::ref.x)
or something similar?
Solución
This question gets asked from time to time
Is Pointer-to- " inner struct" member forbidden?
Basically, this can be described is a rather obvious initial oversight in the design of C++ language, which has has been ignored ever since due to the fact that the language develops in higher-level directions. Pointers of pointer-to-data member type are probably considered too low-level to be given enough attention. I wouldn't be surprised to discover one day that such pointers are deprecated instead of being developed further.
To repeat my statement from the linked answer, the low-level support is already there in every C++ compiler (since the low-level mechanism is the same regardless how deeply the member is "nested" - it is simply the offset of the member on the containing object), but the corresponding initialization syntax is missing.
Otros consejos
Would not just use a plain int*
pointer? Why does it need to be a member pointer?
void doSomethingToVal(int * val)
{
if(val)
{
std::cout << *val;
}
}
int *ptr = &(B::ref.x);
doSomethingToVal(ptr) ;