递归应用运算符> [英] recursive application of operator->

查看:113
本文介绍了递归应用运算符>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据说递归应用箭头运算符。但是当我尝试执行下面的代码,它打印乱码当它应该打印4。

It is said that the arrow operator is applied recursively. But when I try to execute the following code, it prints gibberish when it is supposed to print 4.

class dummy
{
public:
    int *p;

    int operator->()
    {
        return 4;
    }
};

class screen 
{
public:
    dummy *p;

    screen(dummy *pp): p(pp){}
    dummy* operator->()
    {
        return p;
    }
};

int main()
{
    dummy *d = new dummy;
    screen s(d);
    cout<<s->p;
    delete d;
}


推荐答案

Stanley 只是将运算符应用于每个返回的对象,直到返回的类型是一个指针。

What Stanley meant by "recursive" is just that the operator is applied to every returned object until the returned type is a pointer.

screen :: operator - > 返回一个指针。因此,这是对编译器尝试的运算符 - > 的最后一次调用。然后,通过查找返回的pointee类型中的成员( dummy p

Which happens here on the first try: screen::operator -> returns a pointer. Thus this is the last call to an operator -> that the compiler attempts. It then resolves the right-hand sice of the operator (p) by looking up a member in the returned pointee type (dummy) with that name.

基本上,每当编译器在代码中找到语法aᵢ-> b ,它本质上应用以下算法:

Essentially, whenever the compiler finds the syntax aᵢ->b in code, it essentially applies the following algorithm:


  1. aᵢ如果是,请解析 *aᵢ的成员 b ,并调用(*aᵢ).b

  2. 另外,尝试解析aᵢ:: operator - >
  1. Is aᵢ of pointer type? If so, resolve member b of *aᵢ and call (*aᵢ).b.
  2. Else, try to resolve aᵢ::operator ->

  1. 成功时,设置aᵢ₊1 =aᵢ:: operator - >()。 Goto 1。

  2. 失败时会产生编译错误。

  1. On success, set aᵢ₊₁ = aᵢ::operator ->(). Goto 1.
  2. On failure, emit a compile error.


我很难想出一个简短的,有意义的例子,其中 operator - > 调用甚至有意义。可能唯一真正的用途是当你写一个智能指针类。

I’m hard-pressed to come up with a short, meaningful example where a chain of operator -> invocations even makes sense. Probably the only real use is when you write a smart pointer class.

然而,下面的玩具示例至少编译并产生一个数字。但我不建议实际写这样的代码。它破坏封装,使小猫哭泣。

However, the following toy example at least compiles and yields a number. But I wouldn’t advise actually writing such code. It breaks encapsulation and makes kittens cry.

#include <iostream>

struct size {
    int width;
    int height;
    size() : width(640), height(480) { }
};

struct metrics {
    size s;
    size const* operator ->() const {
        return &s;
    }
};

struct screen {
    metrics m;
    metrics operator ->() const {
        return m;
    }
};

int main() {
    screen s;
    std::cout << s->width << "\n";
}

这篇关于递归应用运算符&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆