递归应用运算符> [英] recursive application of operator->
问题描述
据说递归应用箭头运算符。但是当我尝试执行下面的代码,它打印乱码当它应该打印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 $ c $)来解析运算符的右手sice(
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:
- 是
aᵢ
如果是,请解析*aᵢ
的成员b
,并调用(*aᵢ).b
。 - 另外,尝试解析
aᵢ:: operator - >
- Is
aᵢ
of pointer type? If so, resolve memberb
of*aᵢ
and call(*aᵢ).b
. - Else, try to resolve
aᵢ::operator ->
- 成功时,设置
aᵢ₊1 =aᵢ:: operator - >()
。 Goto 1。 - 失败时会产生编译错误。
- On success, set
aᵢ₊₁ = aᵢ::operator ->()
. Goto 1. - 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";
}
这篇关于递归应用运算符>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!