下面是我的代码示例:
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没有运算符->,从而在层次结构中越走越高。
有人能解释这种有趣的行为吗?:)
发布于 2011-02-04 17:15:38
因为这就是C++中重载->
的工作方式。
使用重载->
时,expression a->b
将转换为a.operator->()->b
。这意味着重载的运算符->
必须返回本身支持运算符->
的另一个应用程序的内容。由于这个原因,一个重载的->
调用可能会变成一长串重载的->
调用,直到它最终到达内置->
的应用程序,从而结束这个链。
在本例中,您需要从过载的->
返回X*
,而不是X&
。
发布于 2011-02-04 17:47:57
您可能需要:
class Y : public X
{
public:
X* operator->() { return this; }
void f() {}
};
https://stackoverflow.com/questions/4896238
复制相似问题