重载运算符 - > [英] Overloading operator ->
问题描述
这是我的代码示例:
class X
{
public:
void f() {}
};
class Y : public X
{
public:
X& operator->() { return *this; }
void f() {}
};
int main()
{
Y t;
t.operator->().f(); // OK
t->f(); // error C2819: type 'X' does not have an overloaded member 'operator ->'
// error C2232: '->Y::f' : left operand has 'class' type, use '.'
}
为什么编译器试图 >从Y到X?当我实现X :: op->然后我不能返回X那里 - 编译错误说无限递归,而从X :: op->返回一些Z再次说,Z没有operator->,因此更高和
Why the compiler is trying to "move the responsibility" for operator-> from Y to X? When I implement X::op-> then I cannot return X there - compile error says "infinite recursion" while returning some Z from X::op-> again says that Z doesn't have operator->, thus going higher and higher in hierarchy.
任何人都可以解释这个有趣的行为吗? :)
Can anyone explain this interesting behavior? :)
推荐答案
问题是, operator - >
以返回指针,而不是 。这个想法是 operator - >
应该返回一个指向应该有指针的实际对象的指针。例如,对于具有重载运算符 - >
的类,代码
The problem is that operator ->
is supposed to return a pointer, not a reference. The idea is that operator ->
should return a pointer to the real object that should have the pointer applied to it. For example, for a class with an overloaded operator ->
, the code
myClass->myValue;
可转换为
(myClass.operator-> ())->myValue;
您的代码的问题是 operator - >
返回一个引用,所以写
The problem with your code is that operator ->
returns a reference, so writing
myClass.operator->().f();
完全合法,因为您明确调用该运算符,但写
is perfectly legal because you're explicitly invoking the operator, but writing
myClass->f();
是非法的,因为编译器尝试将其扩展到
is illegal, because the compiler is trying to expand it to
myClass.operator->()->f();
,返回类型 operator->
不是指针。
为了解决这个问题,修改代码,以便在 operator - >
。如果你想重载一个操作符来返回一个引用,重载 operator *
;指针解引用确实会产生引用。
To fix this, change your code so that you return a pointer in operator ->
. If you want to overload an operator to return a reference, overload operator *
; pointer dereferences should indeed produce references.
这篇关于重载运算符 - >的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!