超载-> c++ 中的运算符
我看到了这段代码,但我无法理解它的作用:
inline S* O::operator->() const
{
return ses; //ses is a private member of Type S*
}
那么如果我使用 ->
现在会发生什么?
I saw this code but I couldn't understand what it does:
inline S* O::operator->() const
{
return ses; //ses is a private member of Type S*
}
so what happens now if I used ->
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
现在,如果您
首先调用重载的
operator->
,它将返回存储在对象内的ses
,然后operator->
(在S*
的情况下是内置的)将再次调用返回的指针。So
相当于伪代码:
后者当然是不可能的,因为
O::ses
是private
- 这就是为什么我称其为伪代码。通过这样的重载,您可以围绕指针创建一个包装器 - 这种包装器通常称为智能指针。
Now if you have
first the overloaded
operator->
will be called, which will returnses
stored inside the object, thenoperator->
(built-in in case ofS*
) will be called again for the returned pointer.So
is equivalent to pseudocode:
the latter would be of course impossible since
O::ses
isprivate
- that's why I call it pseudocode.With such overload you can create a wrapper around a pointer - such wrapper is typically called smart pointer.
如果你有一个类 O 的实例,
那么你就执行操作符->返回 ses,然后使用返回的指针调用 func()。
完整示例:
Is you have an instance of class O and you do
then the operator-> returns ses and then it uses the returned pointer to call func().
Full example:
它是一个重载运算符,将返回指向
S
类型的某个成员的指针。就像,如果您编写
(object->)
部分将成为您的指针。It's an overloaded operator that would return a pointer to some member of type
S
.Like, if you write
the part
(object->)
would become your pointer.任何时候 O 类型的对象使用 ->;运算符将返回指向 ses 的指针。
Anytime an object of type O uses the -> operator a pointer to ses will be returned.
它使运算符重载 ->属于 O 类,现在返回 S* 而不是 O*
It overloads the operator -> of the class O, that returns now an S* instead of an O*