Pointer to a pointer attribute

Is there any way to simulate this situation in C ++?

I have two objects Aand B, each of which has one attribute, for example int i; I also have one pointer popointing to an object and one pointer pipointing to an integer. I want to have an integer pointer pointing to an attribute in the current object that the pointer points to. Sort of:

po = A;
pi = po->i;
// pi points to A.i
po = B;
// now pi points to B.i

I am pretty sure that this cannot be achieved with pointers, but I want to know if there is work there for this.

+3
source share
8 answers

What you are looking for is called member pointers. Suppose A and B are of type T, then you can write:

struct T { int i; };
T A, B, C; // some objects of this type

int T::*pi = &T::i; // pi is a pointer to an int member of T

T* po;
po = &A;
cout << po->*pi << '\n'; // prints A.i
po = &B;
cout << po->*pi << '\n'; // prints B.i

cout << C.*pi << '\n'; // prints C.i
+4

. pi /, po . pi pe AutoReference, , . , " ": , .

class AutoReference
{
public:
  AutoReference( ClassA ** ppObj )
  : mppObj( ppObj )
  {
  }

  ClassA * operator->()
  {
    return *mppObj;
  }

private:
  ClassA ** mppObj;
};


po = A;
AutoReference pi( &po );
// pi "points" to A.i
po = B;
// now pi "points" to B.i
+2
struct O
{
    int i;
};

struct P
{
    void operator=(O & rhs)
    {
        po = &rhs;
        pi = &rhs.i;
    }

    O * po;
    int * pi;
};

int main()
{
    P po;
    int *& pi = po.pi;

    O A,B;
    A.i = 7;
    B.i = 19;

    po = A;
    cout << *pi << endl;
    po = B;   
    cout << *pi << endl;
}
+2

, .

T a, b;
a.i = 6;
b.i = 9;

T* po = &a;
T** pi = &po;
std::cout << (*pi)->i;  // Prints 6

po = &b;
std::cout << (*pi)->i;  // Prints 9
+1

:

pi A.i, po B.

po = &A;
// do stuff using po and po->i (A and A.i)

po = &B;
// do stuff using po and po->i (B and B.i)
0

, , . .

, , , . , . .

, , , , , - . , :

po = A;
int ai = po->i;
po = B;
int ab = po->i;

, ?

0

, .

class MyObject
{
public:
 int m_i;

};

class AutomaticPointerToMember
{
    public:
 AutomaticPointerToMember(MyObject& obj,int MyObject::*):
 m_Object(obj),
 m_pInt(NULL)
 {}

    operator int* ()
 {
  return &(m_Object.*m_pInt);
 }

 int operator* ()
 {
  return (m_Object.*m_pInt);
 }

private:
 MyObject& m_Object;
 int MyObject::* m_pInt;
};

void test()
{
 MyObject a;
 MyObject b;

 MyObject * pObj =  &a;
 AutomaticPointerToMember pi(*pObj, &MyObject::m_i);

 int * pIa = pi; // pIa  points to a.i
    int ia = *pi; // value a.i

 pObj = &b; // pObj now points to b

 int * pIb = pi; // pIb  points to b.i

    int ib = *pi; // value b.i
}

&, & .., ...

0
struct S {
   int i;
};


S a, b;
A * ap = & a;
int * ip = &(ap->i);

ip ( , ++)

-4

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


All Articles