如何直接调用"operator - >()"?

Ann*_*mus 3 c++

出于某些奇怪的原因,我需要直接调用operator - >()方法.例如:

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

class ARef {
    public:
        A* operator->() { return a; }
    protected:
        A* a;
}; 
Run Code Online (Sandbox Code Playgroud)

如果我有一个ARef对象,我可以通过编写来调用foo():

aref->foo();
Run Code Online (Sandbox Code Playgroud)

但是,我想获得指向受保护成员'a'的指针.我怎样才能做到这一点?

In *_*ico 11

aref.operator->(); // Returns A*
Run Code Online (Sandbox Code Playgroud)

请注意,此语法也适用于所有其他运算符:

// Assuming A overloads these operators
A* aref1 = // ...
A* aref2 = // ...
aref1.operator*();
aref1.operator==(aref2);
// ...
Run Code Online (Sandbox Code Playgroud)

为了更清晰的语法,您可以实现一个Get()函数或重载*运算符,以便&*aref按照James McNellis的建议.


Jam*_*lis 5

您可以使用以下语法直接调用运算符:

aref.operator->()
Run Code Online (Sandbox Code Playgroud)

你或许应该都过载->*,这样的用法是用指针的用法是一致的:

class ARef {
    public:
        A* operator->() { return a; }
        A& operator*() { return *a; }
    protected:
        A* a;
}; 
Run Code Online (Sandbox Code Playgroud)

然后,您可以使用以下内容来获取指针值:

&*aref
Run Code Online (Sandbox Code Playgroud)

您还可以实现直接get()返回的成员函数A*,这比这些解决方案中的任何一个都要清晰得多(大多数智能指针类提供get()成员函数).