c++ 中的运算符重载
struct T
{
int a;
int b;
};
class Ptr
{
public:
Ptr(int a, int b) { t_.a = a; t_.b = b; }
T* operator->() {return &t_;}
T& operator*() {return t_;}
private:
T t_;
};
int main()
{
Ptr ptr(1, 2);
cout << "a = " << ptr->a << " b = " << ptr->b << endl;
cout << "a = " << ptr.operator->()->a << " b = " << ptr.operator->()->b << endl;
}
输出:
a = 1 b = 2
a = 1 b = 2
为什么ptr->a
和ptr.operator->()->a
一样,其中的原理是什么?
struct T
{
int a;
int b;
};
class Ptr
{
public:
Ptr(int a, int b) { t_.a = a; t_.b = b; }
T* operator->() {return &t_;}
T& operator*() {return t_;}
private:
T t_;
};
int main()
{
Ptr ptr(1, 2);
cout << "a = " << ptr->a << " b = " << ptr->b << endl;
cout << "a = " << ptr.operator->()->a << " b = " << ptr.operator->()->b << endl;
}
Output:
a = 1 b = 2
a = 1 b = 2
Why is ptr->a
the same as ptr.operator->()->a
, what's the principle in it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
因为这就是这个重载运算符的工作原理......
Because this is how this overloaded operator works...
这就是规则。重载运算符时->它必须返回一个指针或其他具有重载运算符 -> 的东西并且递归地应用该运算符,直到返回指针为止。最终 ->应用于该指针。这个规则是有道理的。否则你会期望运算符 ->再举一个论点。但什么类型的呢?细绳?当然不是。我的意思是,想一想,这是最(如果不是唯一)合理的方式。从这个意义上说,运算符 ->可以说是一个例外。
That's the rule. When overloading operator -> it must return either a pointer or something else that has overloaded operator -> and that operator is applied recursively until a pointer is returned. And the evenutal -> is applied to that pointer. The rule makes sense. Otherwise you'd expect that operator -> take another argument. But of what type? string? Naturally not. I mean, think about it, this is the most (if not only) reasonable way. In this sense operator -> can be said tobe an exception.