如何创建和使用类箭头运算符?

Cod*_*ith 22 c++ class operator-keyword

因此,在研究了它到处之后,我似乎无法找到如何创建类箭头操作符,即

class Someclass
{
  operator-> ()  /* ? */
  {
  }
};
Run Code Online (Sandbox Code Playgroud)

我只需要知道如何使用它并适当地使用它. - 它的投入是什么? - 它返回什么? - 我如何正确声明/原型化?

Dan*_*her 29

箭头操作符没有输入.从技术上讲,它可以返回你想要的任何东西,但它应该返回一个指针或者可以通过链式->运算符成为指针的东西.

使用内置指针取消引用->调用其参数之前,运算符会自动取消引用其返回值,因此您可以使用以下类:operator*

class PointerToString
{
    string a;

public:
    class PtPtS
    {
    public:
        PtPtS(PointerToString &s) : r(s) {}
        string* operator->()
        {
            std::cout << "indirect arrow\n";
            return &*r;
        }
    private:
        PointerToString & r;
    };

    PointerToString(const string &s) : a(s) {}
    PtPtS operator->()
    {
        std::cout << "arrow dereference\n";
        return *this;
    }
    string &operator*()
    {
        std::cout << "dereference\n";
        return a;
    }
};
Run Code Online (Sandbox Code Playgroud)

使用它像:

PointerToString ptr(string("hello"));
string::size_type size = ptr->size();
Run Code Online (Sandbox Code Playgroud)

由编译器转换为:

string::size_type size = (*ptr.operator->().operator->()).size();
Run Code Online (Sandbox Code Playgroud)

(尽可能多.operator->()地返回一个真正的指针)并且应该输出

arrow dereference
indirect dereference
dereference
Run Code Online (Sandbox Code Playgroud)

但请注意,您可以执行以下操作:

PointerToString::PtPtS ptr2 = ptr.operator->();
Run Code Online (Sandbox Code Playgroud)

在线运行:https://wandbox.org/permlink/Is5kPamEMUCA9nvE

来自Stroupstrup:

对象的变换p为指针p.operator->()不依赖于所述构件指向.这就是operator->()一元后缀运算符的意义.但是,没有引入新的语法,因此在之后仍然需要成员名称->


小智 24

运算符 - >用于重载成员访问.一个小例子:

#include <iostream>
struct A 
{
    void foo() {std::cout << "Hi" << std::endl;}
};

struct B 
{
    A a;
    A* operator->() {
        return &a;
    }
};

int main() {
    B b;
    b->foo();
}
Run Code Online (Sandbox Code Playgroud)

这输出:

Hi
Run Code Online (Sandbox Code Playgroud)