How do I call "operator->()" directly?
For some strange reason, I need to call the operator->() method directly. For example:
class A {
public:
void foo() { printf("Foo"); }
};
class ARef {
public:
A* operator->() { return a; }
protected:
A* a;
};
If I have an ARef obje开发者_StackOverflow社区ct, I can call foo() by writing:
aref->foo();
However, I want to get the pointer to the protected member 'a'. How can I do this?
aref.operator->(); // Returns A*
Note that this syntax works for all other operators as well:
// Assuming A overloads these operators
A* aref1 = // ...
A* aref2 = // ...
aref1.operator*();
aref1.operator==(aref2);
// ...
For a cleaner syntax, you can a implement a Get()
function or overload the *
operator to allow for &*aref
as suggested by James McNellis.
You can call the operator directly using the following syntax:
aref.operator->()
You should probably overload both ->
and *
, so that usage is consistent with the usage of a pointer:
class ARef {
public:
A* operator->() { return a; }
A& operator*() { return *a; }
protected:
A* a;
};
Then you can use the following to get the pointer value:
&*aref
You can also implement a get()
member function that returns the A*
directly, which is much, much cleaner than either of these solutions (most smart pointer classes provide a get()
member function).
You can call operator->()
directly.
A* result = a.operator->();
I would probably not call it together, but instead create a new member which does the same work since it would read better:
class ARef {
public:
A* operator->() { return get(); }
A* get() const { return a; }
protected:
A* a;
};
Absent any friends, you cannot get a "pointer to the protected member a
" outside class A
or one of its descendants. Operator ->
will not help you here, regardless of how you call it.
Given the current interface of ARef
, the only way to get a pointer to a
is to do something like A **pa = &a
inside one of the methods of class A
or some descendant class.
I don't know why you need to get a pointer to a
, and frankly it doesn't seem to make much practical sense to me, but if you really need it, you can add a separate method that does exactly that
class ARef {
public:
...
A** get_ptr_to_a() { return &a; }
...
};
精彩评论