()" directly? For some strange reason, I need to call the operator → () method directly. For instance: class A { ...">

How can I call "operator -> ()" directly?

For some strange reason, I need to call the operator → () method directly. For instance:

class A {
    public:
        void foo() { printf("Foo"); }
};

class ARef {
    public:
        A* operator->() { return a; }
    protected:
        A* a;
}; 

If I have an ARef object, I can call foo () by writing:

aref->foo();

However, I want to get a pointer to the protected member 'a'. How can i do this?

+3
source share
5 answers
aref.operator->(); // Returns A*

Note that this syntax also works for all other operators:

// Assuming A overloads these operators
A* aref1 = // ...
A* aref2 = // ...
aref1.operator*();
aref1.operator==(aref2);
// ...

For a cleaner syntax, you can implement the function Get()or overload the operator *to allow &*aref, as suggested by James McNellis .

+10
source

You can invoke the statement directly using the following syntax:

aref.operator->()

, ->, *, :

class ARef {
    public:
        A* operator->() { return a; }
        A& operator*() { return *a; }
    protected:
        A* a;
}; 

, :

&*aref

- get(), A* , , , ( get()).

+5

operator->().

A* result = a.operator->();
+3

, , , , , :

class ARef {
public:
    A* operator->() { return get(); }
    A* get() const { return a; }
protected:
    A* a;
};
+2

, " a" a . -> , , .

ARef, a - - A **pa = &a a .

, a, , , , , , ,

class ARef {
public:
  ...
  A** get_ptr_to_a() { return &a; }
  ...
};
+2

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


All Articles